Ok, so I generate some formatted text and I store it in the inventory title. But when I want to parse that inventory title, normal string operations don’t work, as it’s been changed by coloring it.
Is there a way to get plain string from a formatted string?
If I do this System.out.println("Player just tried to click on the following inventory: \""+ Text.builder(e.getTargetInventory().getName().get()).style(TextStyles.RESET).build().toPlain() +"\"!");
the output is formatted (in the same way input is)
and then the String#contains() doesn’t work properly
I personally had this issue not too long ago. Depending on how the text is built (typically with the chat colour codes) it won’t be able to become plain even after the toPlain function.
I got around this issue by calling it to plain, and then stripping the colour codes from the String output. As shown in my code below (I had the benefit of using a compatibility layer between sponge and Bukkit so thats why its needing to be references in two classes)
As you are probably not using a compatibility layer you can simply use a for loop.
Hmm… somehow the last piece of code doesn’t do anything…
My current code and the response
@Listener
public void onInventoryClicked(ClickInventoryEvent e) {
String title = e.getTargetInventory().getName().get();
for(TextColor colour : Sponge.getRegistry().getAllOf(TextColor.class)){
System.out.println("replacing "+colour.toString());
title = title.replace(colour.toString(), "");
}
System.out.println("Player just tried to click on the following inventory: \""+ title +"\"!");
}
Response:
[19:08:35 INFO] [STDOUT]: replacing dark_red
[19:08:35 INFO] [STDOUT]: replacing green
[19:08:35 INFO] [STDOUT]: replacing dark_green
[19:08:35 INFO] [STDOUT]: replacing black
[19:08:35 INFO] [STDOUT]: replacing yellow
[19:08:35 INFO] [STDOUT]: replacing NONE
[19:08:35 INFO] [STDOUT]: replacing dark_blue
[19:08:35 INFO] [STDOUT]: replacing dark_purple
[19:08:35 INFO] [STDOUT]: replacing gold
[19:08:35 INFO] [STDOUT]: replacing red
[19:08:35 INFO] [STDOUT]: replacing aqua
[19:08:35 INFO] [STDOUT]: replacing gray
[19:08:35 INFO] [STDOUT]: replacing light_purple
[19:08:35 INFO] [STDOUT]: replacing blue
[19:08:35 INFO] [STDOUT]: replacing white
[19:08:35 INFO] [STDOUT]: replacing dark_aqua
[19:08:35 INFO] [STDOUT]: replacing dark_gray
[19:08:35 INFO] [STDOUT]: replacing reset
[19:08:35 INFO] [STDOUT]: Player just tried to click on the following inventory: "test-842"
Yep. Thats how i did it with my compatibility layer. If minecraft detects a valid chat code it will change the following text into the colour and remove the code. Thats how it works in regular mc and craftbukkit (by extention spigot, paper, etc)