Return same ItemStack with added Lore

Discussion in 'Spigot Help' started by Antaner, Jun 23, 2022 at 11:25 PM.

  1. Hey, how do I get the Enchantments of an ItemStack, onto another with some added Lore? As you can see in the Screenshot I attached, I just tried the most obvious, enchanting the Item with the Enchantments of the ItemStack I want to "copy", but it doesn't work. If you can spot my mistake or have a completely new solution, I'd be very thankful.
     

    Attached Files:

  2. ItemStack#getEnchantments returns a Map<Enchantment, Integer>. ItemMeta#addEnchant only takes a single enchantment and its level - therefore passing a Map naturally won't work - and then a boolean for whether to apply normal enchantment restrictions.
    Instead, you can loop over that Map of enchantments and add each enchantment from it individually, like so:
    Code (Java):
    Map<Enchantment, Integer> enchantments = item.getEnchantments();
    enchantments.forEach((enchantment, level) -> meta.addEnchantment(enchantment, level, false));
    This is also effectively a lambda-ized version of this for-loop, if it helps for clarity:
    Code (Java):
    for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
        meta.addEnchantment(entry.getKey(), entry.getValue(), false);
    }
     
  3. Works perfectly, thank you very much! I'm completely new to Hashmaps, and through your help, I understood them a bit more! Is there any way to check now, if the Item has an enchant? So If it hasn't, i can just add an enchant glint, and hide the enchantment, but if it has enchantments, the enchant glint is no longer necessary, and so is the hiding of the enchantments.
     
  4. Maps have a #isEmpty method. You can just use that to check if there's any existing entries. If not, then add your enchantment and tag the item with ItemFlag.HIDE_ENCHANTMENTS.
    You can't guarantee that the item is yours just by it having one enchantment and the item flag though, so the most reliable way to tell if this is one of your items is probably to use PersistentDataContainer.