下面列出了怎么用org.bukkit.inventory.meta.ItemMeta的API类实例代码及写法,或者点击链接到github查看源代码。
public Location makeSpectator(GamePlayer gamePlayer, boolean leaveItem) {
Player player = gamePlayer.player;
gamePlayer.isSpectator = true;
gamePlayer.teleport(specSpawn, () -> {
player.setAllowFlight(true);
player.setFlying(true);
player.setGameMode(GameMode.SPECTATOR);
if (leaveItem) {
int leavePosition = Main.getConfigurator().config.getInt("hotbar.leave", 8);
if (leavePosition >= 0 && leavePosition <= 8) {
ItemStack leave = Main.getConfigurator().readDefinedItem("leavegame", "SLIME_BALL");
ItemMeta leaveMeta = leave.getItemMeta();
leaveMeta.setDisplayName(i18n("leave_from_game_item", false));
leave.setItemMeta(leaveMeta);
gamePlayer.player.getInventory().setItem(leavePosition, leave);
}
}
});
return specSpawn;
}
public static ItemStack getSelectorItem() {
YAMLConfig config = ConfigOptions.instance.getConfig();
String name = config.getString("petSelector.item.name", "&aPets");
int materialId = config.getInt("petSelector.item.materialId", Material.BONE.getId());
int materialData = config.getInt("petSelector.item.materialData", 0);
List<String> lore = config.config().getStringList("petSelector.item.lore");
if (lore == null) {
lore = new ArrayList<String>();
}
ItemStack i = new ItemStack(materialId, 1, (short) materialData);
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
ArrayList<String> loreList = new ArrayList<String>();
if (lore.size() > 0) {
for (String s : lore) {
loreList.add(ChatColor.translateAlternateColorCodes('&', s));
}
}
if (!loreList.isEmpty()) {
meta.setLore(loreList);
}
i.setItemMeta(meta);
return i;
}
public ItemStack getSpawnerFromEntityType(EntityType entityType) {
ItemStack item = new ItemStack(Objects.requireNonNull(XMaterial.SPAWNER.parseMaterial()));
ItemMeta meta = item.getItemMeta();
String mobFormatted = Chat.uppercaseStartingLetters(entityType.name().toString());
meta.setDisplayName(plugin.getConfigurationHandler().getMessage("global", "name").replace("%mob%", mobFormatted));
List<String> newLore = new ArrayList<>();
if (plugin.getConfigurationHandler().getList("global", "lore") != null && plugin.getConfigurationHandler().getBoolean("global", "lore-enabled")) {
for (String line : plugin.getConfigurationHandler().getList("global", "lore")) {
newLore.add(Chat.format(line).replace("%mob%", mobFormatted));
}
meta.setLore(newLore);
}
item.setItemMeta(meta);
return plugin.getNmsHandler().setType(item, entityType);
}
@Override
public boolean applyMod(Player player, ItemStack tool, boolean isCommand) {
ItemMeta meta = tool.getItemMeta();
if (meta != null) {
if (ToolType.BOW.contains(tool.getType()) || ToolType.CROSSBOW.contains(tool.getType())) {
meta.addEnchant(Enchantment.ARROW_FIRE, modManager.getModLevel(tool, this), true);
} else if (ToolType.SWORD.contains(tool.getType()) || ToolType.AXE.contains(tool.getType())) {
meta.addEnchant(Enchantment.FIRE_ASPECT, modManager.getModLevel(tool, this), true);
}
tool.setItemMeta(meta);
}
return true;
}
/**
* If the player filled up the bucket themselves
*
* @param e - event
*/
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onBucketFill(PlayerBucketFillEvent e) {
if (DEBUG)
plugin.getLogger().info("Player filled the bucket");
if (e.getPlayer().getWorld().getName().equalsIgnoreCase(Settings.worldName)) {
if (DEBUG)
plugin.getLogger().info("Correct world");
if (Settings.acidDamage > 0D && Settings.acidBottle) {
ItemStack item = e.getItemStack();
if (item.getType().equals(Material.WATER_BUCKET) || item.getType().equals(Material.POTION)) {
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(plugin.myLocale(e.getPlayer().getUniqueId()).acidBucket);
lore = Arrays.asList(plugin.myLocale(e.getPlayer().getUniqueId()).acidLore.split("\n"));
meta.setLore(lore);
item.setItemMeta(meta);
}
}
}
}
@Override
public boolean applyMod(Player player, ItemStack tool, boolean isCommand) {
ItemMeta meta = tool.getItemMeta();
if (meta != null) {
if (ToolType.AXE.contains(tool.getType()) || ToolType.SWORD.contains(tool.getType())) {
meta.addEnchant(Enchantment.DAMAGE_ALL, modManager.getModLevel(tool, this), true);
} else if (ToolType.BOW.contains(tool.getType()) || ToolType.CROSSBOW.contains(tool.getType())) {
meta.addEnchant(Enchantment.ARROW_DAMAGE, modManager.getModLevel(tool, this), true);
} else if (ToolType.TRIDENT.contains(tool.getType())) {
meta.addEnchant(Enchantment.DAMAGE_ALL, modManager.getModLevel(tool, this), true);
meta.addEnchant(Enchantment.IMPALING, modManager.getModLevel(tool, this), true);
}
tool.setItemMeta(meta);
}
return true;
}
public Inventory displayLogGUI(final Player player) {
List<String> lores = new ArrayList<>();
String title = "\u00a79" + tr("Island Log");
Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), 9, title);
ItemMeta meta4 = sign.getItemMeta();
meta4.setDisplayName("\u00a79\u00a7l" + tr("Island Log"));
addLore(lores, tr("\u00a7eClick here to return to\n\u00a7ethe main island screen."));
meta4.setLore(lores);
sign.setItemMeta(meta4);
menu.addItem(new ItemStack[]{sign});
lores.clear();
ItemStack menuItem = new ItemStack(Material.WRITABLE_BOOK, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7e\u00a7lIsland Log"));
for (String log : plugin.getIslandInfo(player).getLog()) {
lores.add(log);
}
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.setItem(8, menuItem);
lores.clear();
return menu;
}
public static ItemStack addEnchant(ItemStack item, CEnchantment ce, int level) {
ItemMeta im = item.getItemMeta();
List<String> lore = new ArrayList<String>();
if (im.hasLore()) {
lore = im.getLore();
if (maxEnchants < enchantments.size()) {
int counter = maxEnchants;
for (String s : lore)
if (containsEnchantment(s)) {
counter--;
if (counter <= 0) {
return item;
}
}
}
}
if (level > ce.getEnchantmentMaxLevel())
level = ce.getEnchantmentMaxLevel();
lore.add(ce.getDisplayName() + " " + intToLevel(level));
im.setLore(lore);
item.setItemMeta(im);
item.addUnsafeEnchantment(glowEnchantment, 0);
return item;
}
/**
* Adds lore after the index of a lore line
*
* @param index index
* @param lore lore
* @return builder
*/
public ItemStackBuilder addLore(int index, String... lore) {
final ItemMeta itemMeta = this.getItemMeta();
final List<String> data = new ArrayList<>();
for (int i = 0; i < itemMeta.getLore().size(); i++) {
data.add(itemMeta.getLore().get(0));
if (i == index) {
for (final String s : lore) {
data.add(ChatColor.translateAlternateColorCodes('&', s));
}
}
}
itemMeta.setLore(data);
this.setItemMeta(itemMeta);
return this;
}
/**
* Creates a plain copy of this ItemData. It will have same material,
* amount of 1 and same block values. Tags will also be copied, with
* following exceptions:
* <ul>
* <li>Damage: 1.13 tag-damage is only used for actual durability.
* Present on 1.12 and older versions.
* <li>Name: custom names made with anvil do not change item type
* </ul>
* @return A modified copy of this item data.
*/
public ItemData aliasCopy() {
ItemData data = new ItemData();
data.stack = new ItemStack(type, 1);
if (stack.hasItemMeta()) {
ItemMeta meta = stack.getItemMeta(); // Creates a copy
meta.setDisplayName(null); // Clear display name
data.stack.setItemMeta(meta);
}
if (!itemDataValues) {
ItemUtils.setDamage(data.stack, 0); // Set to undamaged
}
data.type = type;
data.blockValues = blockValues;
data.itemForm = itemForm;
return data;
}
private void setSkin(ItemStack head, String b64stringtexture) {
GameProfile profile = new GameProfile(UUID.randomUUID(), null);
PropertyMap propertyMap = profile.getProperties();
if (propertyMap == null) {
throw new IllegalStateException("Profile doesn't contain a property map");
}
propertyMap.put("textures", new Property("textures", b64stringtexture));
ItemMeta headMeta = head.getItemMeta();
Class<?> headMetaClass = headMeta.getClass();
try {
ReflectionUtil.getField(headMetaClass, "profile", GameProfile.class, 0).set(headMeta, profile);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
head.setItemMeta(headMeta);
}
/**
* Checks the durability of the Tool
*
* @param cancellable the Event (implements Cancelable)
* @param player the Player
* @param tool the Tool
* @return false: if broken; true: if enough durability
*/
public boolean durabilityCheck(@NotNull Cancellable cancellable, @NotNull Player player, @NotNull ItemStack tool) {
ItemMeta meta = tool.getItemMeta();
if (meta instanceof Damageable) {
if (config.getBoolean("UnbreakableTools", true)
&& tool.getType().getMaxDurability() - ((Damageable) meta).getDamage() <= 2) {
cancellable.setCancelled(true);
if (config.getBoolean("Sound.OnBreaking", true)) {
player.playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 0.5F, 0.5F);
}
return false;
}
}
return true;
}
public static void OpenSet(Player p) {
ItemStack close = new ItemStack(Material.REDSTONE_BLOCK, 1);
ItemMeta meta = close.getItemMeta();
meta.setDisplayName("Close");
ArrayList<String> lore = new ArrayList<>();
lore.add("Click to close the inventory and return to normal gameplay");
meta.setLore(lore);
close.setItemMeta(meta);
Inventory set = Bukkit.createInventory(p, 27, "WildTp");
p.openInventory(set);
set.setItem(0, MainGui.makeItem(Material.valueOf(MainGui.getMaterials().get("Book")), "MinX", Collections.singletonList("Click to set the minx")));
set.setItem(2, MainGui.makeItem(Material.valueOf(MainGui.getMaterials().get("Book")), "MaxX", Collections.singletonList("Click to set the maxx")));
set.setItem(4, MainGui.makeItem(Material.valueOf(MainGui.getMaterials().get("Book")), "MinZ", Collections.singletonList("Click to set the minz")));
set.setItem(6, MainGui.makeItem(Material.valueOf(MainGui.getMaterials().get("Book")), "MaxZ", Collections.singletonList("Click to set the maxz")));
set.setItem(8, MainGui.makeItem(Material.valueOf(MainGui.getMaterials().get("Watch")), "Cooldown", Collections.singletonList("Click me to set the cooldown for the command")));
set.setItem(10, MainGui.makeItem(Material.GOLD_BLOCK, "Cost", Collections.singletonList("Click me to set the cost for the command")));
set.setItem(12, MainGui.makeItem(Material.valueOf(MainGui.getMaterials().get("Watch")), "Wait", Collections.singletonList("Click to set the wait before telepoting happens")));
set.setItem(14, MainGui.makeItem(Material.valueOf(MainGui.getMaterials().get("Watch")), "Retries", Collections.singletonList("Click to set the number of retries if a location is unsuitable")));
set.setItem(16, MainGui.makeItem(Material.valueOf(MainGui.getMaterials().get("Watch")), "Do Retry", Collections.singletonList("Click to set true or false for doing retries")));
set.setItem(18, MainGui.makeItem(Material.MAP, "Distance", Arrays.asList("Click to set the distance the plugin checks for a claim")));
set.setItem(24, MainGui.backItem());
set.setItem(26, close);
}
public ItemStack setDisplayName(String s, ItemStack i){
ItemStack t = i.clone();
s = ChatColor.translateAlternateColorCodes('&', s);
ItemMeta m = i.getItemMeta();
m.setDisplayName(s);
t.setItemMeta(m);
return t;
}
public static NBTTagCompound getTagFromMeta(Material type, ItemMeta meta) {
Preconditions.checkNotNull(meta, "Null meta");
Preconditions.checkNotNull(type, "Null type");
Preconditions.checkArgument(Bukkit.getItemFactory().isApplicable(meta, type), "Meta %s isn't applicable to %s", meta, type);
Item item = CraftMagicNumbers.getItem(type);
ItemStack stack = new ItemStack(item);
boolean worked = CraftItemStack.setItemMeta(stack, meta);
if (!worked) throw new RuntimeException("Didn't work");
return stack.getTag();
}
public static boolean itemHasName(ItemStack stack, String name)
{
if(stack == null)
return false;
ItemMeta meta = stack.getItemMeta();
if(meta == null)
return false;
if(!meta.hasDisplayName())
return false;
return meta.getDisplayName().equalsIgnoreCase(name);
}
@Override
protected void setUp()
{
teleporters = new HashMap<UUID,Teleporter>();
transporterItem = KitUtils.addSoulbound(new ItemStack(Material.QUARTZ));
ItemMeta m = transporterItem.getItemMeta();
m.setDisplayName(transporterItemName);
transporterItem.setItemMeta(m);
}
public static ItemStack addEnchantments(ItemStack item, HashMap<CEnchantment, Integer> list) {
ItemMeta im = item.getItemMeta();
List<String> lore = new ArrayList<String>();
if (im.hasLore()) {
lore = im.getLore();
if (maxEnchants < enchantments.size()) {
int counter = maxEnchants - list.size();
for (String s : lore)
if (containsEnchantment(s)) {
counter--;
if (counter <= 0) {
return item;
}
}
}
}
for (CEnchantment ce : list.keySet()) {
int level = list.get(ce);
if (level > ce.getEnchantmentMaxLevel())
level = ce.getEnchantmentMaxLevel();
lore.add(ce.getDisplayName() + " " + intToLevel(level));
}
im.setLore(lore);
item.setItemMeta(im);
item.addUnsafeEnchantment(glowEnchantment, 0);
return item;
}
/**
* Prevents enhanced item dropped from death.
*
* @param e
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerDeath(PlayerDeathEvent e) {
Player p = e.getEntity();
List<ItemStack> newInventory = new ArrayList<ItemStack>();
File playerFile = new File(m.getDataFolder() + "/death/" + p.getName() + ".yml");
FileConfiguration pFile = YamlConfiguration.loadConfiguration(playerFile);
pFile.set("PlayerName", p.getName());
if (!e.getDrops().isEmpty() || e.getDrops() != null) {
for (int i = 0; i < e.getDrops().size(); i++) {
ItemStack stack = e.getDrops().get(i);
if (stack.hasItemMeta()) {
ItemMeta meta = stack.getItemMeta();
if (meta.hasLore()) {
List<String> lore = meta.getLore();
for (String s : lore) {
s = ChatColor.stripColor(s);
if (s.contains(ChatColor.stripColor(Util.toColor(SettingsManager.lang.getString("lore.untradeableLore"))))
|| s.contains(ChatColor.stripColor(Util.toColor(SettingsManager.lang.getString("lore.tradeableLore"))))) {
newInventory.add(e.getDrops().get(i));
}
}
}
}
}
ItemStack[] newStack = newInventory.toArray(new ItemStack[newInventory.size()]);
pFile.set("Items", newStack);
try {
pFile.save(playerFile);
} catch (IOException e1) {
}
e.getDrops().removeAll(newInventory);
}
}
/**
* Sets damage/durability of an item if possible.
* @param stack Item to modify.
* @param damage New damage. Note that on some Minecraft versions,
* this might be truncated to short.
*/
@SuppressWarnings("deprecation")
public static void setDamage(ItemStack stack, int damage) {
if (damageMeta) {
ItemMeta meta = stack.getItemMeta();
if (meta instanceof Damageable) {
((Damageable) meta).setDamage(damage);
stack.setItemMeta(meta);
}
} else {
stack.setDurability((short) damage);
}
}
@Override
protected void setUp()
{
sucItem = KitUtils.addSoulbound(getIcon().clone());
ItemMeta m = sucItem.getItemMeta();
m.setDisplayName(sucItemName);
sucItem.setItemMeta(m);
Delays.getInstance().createNewDelay(getInternalName(), new StandardItemUpdater(sucItemName,sucItem.getType(),new Function<ItemStack,Boolean>(){
@Override
public Boolean apply(ItemStack stack)
{
return isSuccubusItem(stack);
}}));
}
public ItemMeta handleItemFlags(ItemMeta itemMeta, List<String> flags) {
if (flags.size() > 0) {
for (String flag : flags) {
try {
ItemFlag itemFlag = ItemFlag.valueOf(flag.toUpperCase());
if (itemFlag != null) {
itemMeta.addItemFlags(itemFlag);
}
} catch (Exception ignored) {
}
}
}
return itemMeta;
}
@Override
public void giveStackingStick(Player player){
ItemStack stack = new ItemStack(material, 1);
stack.addUnsafeEnchantment(Enchantment.DURABILITY,1);
ItemMeta stackMeta = stack.getItemMeta();
stackMeta.setDisplayName(itemName);
stackMeta.setLore(itemLore);
stack.setItemMeta(stackMeta);
player.getInventory().addItem(stack);
}
public void onClick(InventoryClickEvent event) {
ItemStack currentItem = event != null ? event.getCurrentItem() : null;
if (event == null || currentItem == null) {
return; // Bail out, nothing we can do anyway
}
Player p = (Player) event.getWhoClicked();
ItemMeta meta = currentItem.getItemMeta();
SkullMeta skull = meta instanceof SkullMeta ? (SkullMeta) meta : null;
if (!(event.getInventory().getHolder() instanceof UltimateHolder))
return;
String inventoryName = stripFormatting(((UltimateHolder) event.getInventory().getHolder()).getTitle());
int slotIndex = event.getSlot();
int menuSize = event.getInventory().getSize();
if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Group Members")))) {
onClickPartyMenu(event, currentItem, p, meta, skull, slotIndex);
} else if (inventoryName.contains(stripFormatting(tr("Permissions")))) {
onClickPermissionMenu(event, currentItem, p, inventoryName, slotIndex);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Biome")))) {
onClickBiomeMenu(event, currentItem, p, slotIndex);
} else if (inventoryName.contains(stripFormatting(tr("Challenge Menu")))) {
onClickChallengeMenu(event, currentItem, p, inventoryName);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Log")))) {
onClickLogMenu(event, p, slotIndex);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Menu")))) {
onClickMainMenu(event, currentItem, p, slotIndex);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Create Menu")))) {
onClickCreateMenu(event, p, meta, slotIndex, menuSize);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Restart Menu")))) {
onClickRestartMenu(event, p, meta, slotIndex, currentItem);
} else if (inventoryName.startsWith(stripFormatting(tr("Config:"))) && event.getWhoClicked() instanceof Player) {
plugin.getConfigMenu().onClick(event);
}
}
public ItemMeta asMetaFor(ItemMeta meta, Material material) {
Validate.notNull(material, "Material cannot be null");
if (!(meta instanceof CraftMetaItem)) {
throw new IllegalArgumentException("Meta of " + (meta != null ? meta.getClass().toString() : "null") + " not created by " + CraftItemFactory.class.getName());
}
return getItemMeta(material, (CraftMetaItem) meta);
}
/**
* adds given lore to the end of other lore.
*/
public static ItemStack addLore(ItemStack item, String[] lores) {
ItemMeta meta = item.getItemMeta();
itemMetaNullCheck(item);
List<String> list = meta.getLore();
if (list == null) {
list = new LinkedList<String>();
}
list.addAll(Arrays.asList(lores));
meta.setLore(list);
item.setItemMeta(meta);
return item;
}
public static ItemStack getGhastTear(Player player, int count) {
ItemStack raindrops = new ItemStack(Material.GHAST_TEAR);
ItemMeta meta = raindrops.getItemMeta();
meta.setDisplayName(ChatColor.AQUA + "Raindrops" + ChatColor.DARK_PURPLE + " | " + ChatColor.WHITE + String.format("%,d", count));
raindrops.setItemMeta(meta);
return raindrops;
}
Element(Material mat, String name) {
this.name = name;
this.itemStack = new ItemStack(mat);
ItemMeta checksName = itemStack.getItemMeta();
checksName.setDisplayName(name);
itemStack.setItemMeta(checksName);
}
public static <T, Z> boolean hasTag(@NotNull ItemStack item, @NotNull String key, PersistentDataType<T, Z> dataType, boolean useMinecraft) {
ItemMeta meta = item.getItemMeta();
if (meta == null) return false;
PersistentDataContainer container = meta.getPersistentDataContainer();
return container.has((useMinecraft ? NamespacedKey.minecraft(key) : new NamespacedKey(MineTinker.getPlugin(), key)), dataType);
}
public static <T, Z> void setTag(@NotNull ItemStack item, @NotNull String key, Z value, PersistentDataType<T, Z> dataType, boolean useMinecraft) {
ItemMeta meta = item.getItemMeta();
if (meta == null) return;
PersistentDataContainer container = meta.getPersistentDataContainer();
container.set((useMinecraft ? NamespacedKey.minecraft(key) : new NamespacedKey(MineTinker.getPlugin(), key)), dataType, value);
item.setItemMeta(meta);
}