Replacing part of the message with a TextComponent with hover

Discussion in 'Spigot Plugin Development' started by MinecraftMart, Oct 2, 2016.

  1. So I build a TextComponent with a hover event in it. And right now I am trying to replace [item] with that TextComponent.

    Code (Text):
        @EventHandler(priority= EventPriority.LOWEST)
        public void onChat(AsyncPlayerChatEvent event)
            Player player = event.getPlayer();
            String message = event.getMessage();

            String displayName = player.getInventory().getItemInMainHand().getItemMeta().getDisplayName();

            TextComponent mes = new TextComponent(displayName);
            mes.setHoverEvent( new HoverEvent( HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(displayName + "\n K").create() ) );

            message = message.replace("[item]", "");

    Any idea on how I would do this?

    (its not about replacing a string, its about replacing the string with the TextComponent)

    #1 MinecraftMart, Oct 2, 2016
    Last edited: Oct 2, 2016
  2. Replace hinges on regex, and both [ and ] are special characters showing regex. You can escape the characters (to make the function see that it's looking for a specific string, not necessarily a regex), by putting a backslash before each bracket. This'll make it look something like this:
    Code (Text):
    message = message.replace("\[item]\", "");
  3. seems like you don't know the difference between .replace and .replaceAll.
    To keep it short: replaceAll is for regular expressions, replace for normal strings.

    And \[ will not compile, only \\[
    • Agree Agree x 2
  4. Thanks for the answers, but I might have explained my problem wrong. Replacing a string works just fine. But its Spigots TextComponent I cant replace it with. Since I added a HOVER action I need to replace the string with the TextComponent object and if I just do .toText then it wont have that hover function.