0

Hello Support I can't get the String from a Component. I did this with 2 ways with bad results.

TextComponent textComponent = (TextComponent) item.displayname;
return textComponent.content();

The result of this is a error with Casting

and

return PlainTextComponentSerializer.plainText().serialize(item.displayname);

The result of this is Literaly "chat.square_brackets" which is weird.

Please Help. Thanks

Fender Selim
  • 65
  • 1
  • 2
  • 8

2 Answers2

1

I also was having trouble with this. Here's what I found to work for me. Full disclosure that I'm developing my plugin on the PaperMC 1.16 fork and not Spigot. So it's possible that this may not work for you, either because it isn't a part of Spigot or because you are working in a version that this feature is not a part of.

To start, I would first check to make sure that we are both on the same page. For me, the component objects being used are from a package called net.kyori.adventure.text if yours are not provided by this package I don't know that this solution will work for you.

Also as mentioned by others, accessing the displayName directly on the ItemStack isn't going to give the desired results. Instead, you need to do itemStack.getItemMeta().displayName(). This method should then return a net.kyori.adventure.text.Component; once you have the component you need to serialize it using one of the serializers from the previously mentioned package.

That will look something like this:

Component itemDisplayName = itemStack.getItemMeta().displayName()

PlainComponentSerializer plainSerializer = PlainComponentSerializer.plain();
String itemName = plainSerializer.serialize(itemDisplayName);

The package that the serializer is from is: net.kyori.adventure.text.serializer.plain.PlainComponentSerializer

Nathan Martin
  • 295
  • 1
  • 3
  • 13
0

I don't understand how you can access to the displayname field in ItemStack in the Spigot API.

You should use ItemMeta to manage display name. To get the item meta, you should use ItemStack#getItemMeta.

Don't forget to check if the item as a meta with hasItemMeta. You can also use hasDisplayName to be sure that the display name is valid.

Elikill58
  • 4,050
  • 24
  • 23
  • 45