Java Code Examples for org.bukkit.event.inventory.InventoryClickEvent#getRawSlot()

The following examples show how to use org.bukkit.event.inventory.InventoryClickEvent#getRawSlot() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InventoryMenu.java    From EchoPet with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onInvClick(InventoryClickEvent event) {
    HumanEntity human = event.getWhoClicked();
    if (human instanceof Player) {
        Player player = (Player) human;
        Inventory inv = event.getView().getTopInventory();
        if (inv.getHolder() != null && inv.getHolder() instanceof InventoryMenu && event.getRawSlot() >= 0 && event.getRawSlot() < size) {
            InventoryMenu menu = (InventoryMenu) inv.getHolder();
            event.setCancelled(true);
            MenuIcon icon = slots.get(event.getSlot());
            if (icon != null) {
                icon.onClick(player);
                player.closeInventory();
            }
        }
    }
}
 
Example 2
Source File: InventoryForVillagerOffers.java    From NBTEditor with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void inventoryClick(InventoryClickEvent event) {
	super.inventoryClick(event);
	int slot = event.getRawSlot();
	if (slot >= 27 && slot < getInventory().getSize()) {
		event.setCancelled(true);
	}
	if (slot >= 27 && slot < 36) {
		changeSelected(slot - 27);
	} else if (slot == 43) {
		// xp reward
		_rewardExp[_selected] = !_rewardExp[_selected];
		updateBottleButton();
		updateWoolButton();
	} else if (slot == 44) {
		// previous page
		changeIndex(event.getWhoClicked(), -9);
	} else if (slot == 53) {
		// next page
		changeIndex(event.getWhoClicked(), +9);
	} else {
		handlePaperButtons(_uses, 36, slot);
		handlePaperButtons(_maxUses, 45, slot);
	}
}
 
Example 3
Source File: BuyingPlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onInventoryClick(InventoryClickEvent event, Player player) {
	event.setCancelled(true);

	int slot = event.getRawSlot();
	if (slot >= 0 && slot <= 7) {
		// modifying cost:
		ItemStack tradedItem = event.getInventory().getItem(slot + 18);
		if (Utils.isEmpty(tradedItem)) return;
		this.handleUpdateTradeCostItemOnClick(event, Settings.createCurrencyItem(1), Settings.createZeroCurrencyItem());
	} else if (slot >= 18 && slot <= 25) {
		// modifying bought item quantity:
		this.handleUpdateItemAmountOnClick(event, 1);
	} else if (slot >= 9 && slot <= 16) {
	} else {
		super.onInventoryClick(event, player);
	}
}
 
Example 4
Source File: LoreGuiItemListener.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOW)
public void OnInventoryClickSecondPhase(InventoryClickEvent event) {
	if (event.isCancelled()) {
		return;
	}
	
	if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
		if (guiInventories.containsKey(event.getView().getTopInventory().getName())) {
			event.setCancelled(true);
			return;
		}
	} else if (event.isShiftClick()) {
		if (guiInventories.containsKey(event.getView().getTopInventory().getName())) {
			event.setCancelled(true);
			return;
		}			
	}
	
}
 
Example 5
Source File: ArmorListener.java    From ViaVersion with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent e) {
    HumanEntity human = e.getWhoClicked();
    if (human instanceof Player && e.getInventory() instanceof CraftingInventory) {
        final Player player = (Player) human;
        if (e.getCurrentItem() != null) {
            if (ArmorType.isArmor(e.getCurrentItem().getTypeId())) {
                sendDelayedArmorUpdate(player);
                return;
            }
        }
        if (e.getRawSlot() >= 5 && e.getRawSlot() <= 8) {
            sendDelayedArmorUpdate(player);
        }
    }
}
 
Example 6
Source File: IconInventory.java    From UHC with MIT License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void on(InventoryClickEvent event) {
    final Inventory inventory = event.getInventory();
    if (!inventory.getTitle().equals(title)) return;

    event.setCancelled(true);

    final int slot = event.getRawSlot();

    if (slot < 0 || slot >= inventory.getSize() || slot >= icons.size()) return;

    // call event
    final IconStack icon = icons.get(slot);

    if (icon != null) {
        icon.onClick((Player) event.getWhoClicked());
    }
}
 
Example 7
Source File: LobbyListener.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
 public void onInventoryClick(final InventoryClickEvent e) {
 	Player player = (Player) e.getWhoClicked();
 	if (Util.get().isSpawnWorld(player.getWorld())) {
 		if (SkyWarsReloaded.getCfg().protectLobby()) {
         	if (!player.hasPermission("sw.alterlobby") && !SkyWarsReloaded.getIC().has(player)) {
         		e.setCancelled(true);
         	}
 		}
     	int rawSlot = e.getRawSlot();
if (e.getInventory().equals(joinMenu) && rawSlot < joinMenu.getSize() && rawSlot >= 0) {
	e.setCancelled(true);
	SWRServer server = SWRServer.getServerByDisplayName(ChatColor.stripColor(SkyWarsReloaded.getNMS().getItemName(e.getCurrentItem())));
             if (server == null) {
                 return;
             }
             
             if (server.getMatchState() != MatchState.WAITINGSTART) {
             	Util.get().playSound(player, player.getLocation(), SkyWarsReloaded.getCfg().getErrorSound(), 1, 1);
             	return;
             }
             
             if (player.hasPermission("sw.join")) {
              if (player!= null) {
              	if (server.getMatchState() == MatchState.WAITINGSTART && server.getPlayerCount() < server.getMaxPlayers()) {
               	player.closeInventory();
               	server.setPlayerCount(server.getPlayerCount() + 1);
     			    	server.updateSigns();
 			    		SkyWarsReloaded.get().sendBungeeMsg(player, "Connect", server.getServerName());
              	}
              }
             }
} 
 	}
 }
 
Example 8
Source File: CrateControl.java    From Crazy-Crates with MIT License 5 votes vote down vote up
@EventHandler
public void onAdminMenuClick(InventoryClickEvent e) {
    Inventory inv = e.getInventory();
    Player player = (Player) e.getWhoClicked();
    if (inv != null && e.getView().getTitle().equals(Methods.sanitizeColor("&4&lAdmin Keys"))) {
        e.setCancelled(true);
        if (!Methods.permCheck(player, "admin")) {
            player.closeInventory();
            return;
        }
        //Added the >= due to an error about a raw slot set at -999.
        if (e.getRawSlot() < inv.getSize() && e.getRawSlot() >= 0) {//Clicked in the admin menu.
            ItemStack item = inv.getItem(e.getRawSlot());
            if (cc.isKey(item)) {
                Crate crate = cc.getCrateFromKey(item);
                if (e.getAction() == InventoryAction.PICKUP_ALL) {
                    player.getInventory().addItem(crate.getKey());
                } else if (e.getAction() == InventoryAction.PICKUP_HALF) {
                    cc.addKeys(1, player, crate, KeyType.VIRTUAL_KEY);
                    String name = null;
                    ItemStack key = crate.getKey();
                    if (key.hasItemMeta() && key.getItemMeta().hasDisplayName()) {
                        name = key.getItemMeta().getDisplayName();
                    }
                    player.sendMessage(Methods.getPrefix() + Methods.color("&a&l+1 " + (name != null ? name : crate.getName())));
                }
            }
        }
    }
}
 
Example 9
Source File: MobFlagGui.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
void onInventoryClick(InventoryClickEvent event) {
    InventoryHolder holder = event.getInventory().getHolder();
    if (holder instanceof Player && holder.equals(this.player)) {

        if (event.getInventory().equals(this.player.getOpenInventory().getTopInventory())) {
            event.setCancelled(true);

            if (event.getRawSlot() == 0) {
                setFlagValue(true);
                close(true);
                return;
            }

            if (event.getRawSlot() == 1) {
                setFlagValue(false);
                close(true);
                return;
            }

            ItemStack item = event.getCurrentItem();
            if (item != null && !item.equals(RedProtect.get().config.getGuiSeparator()) && !item.getType().equals(Material.AIR) && event.getRawSlot() >= 0 && event.getRawSlot() <= this.size - 1) {
                ItemMeta itemMeta = item.getItemMeta();
                List<String> lore = itemMeta.getLore();
                if (lore.get(0).equalsIgnoreCase(translateAlternateColorCodes('&', RedProtect.get().guiLang.getFlagString("value") + " " + RedProtect.get().guiLang.getFlagString("true")))) {
                    lore.set(0, translateAlternateColorCodes('&', RedProtect.get().guiLang.getFlagString("value") + " " + RedProtect.get().guiLang.getFlagString("false")));
                    item.setAmount(1);
                } else {
                    lore.set(0, translateAlternateColorCodes('&', RedProtect.get().guiLang.getFlagString("value") + " " + RedProtect.get().guiLang.getFlagString("true")));
                    item.setAmount(2);
                }
                itemMeta.setLore(lore);
                item.setItemMeta(itemMeta);
            }
        }
    }
}
 
Example 10
Source File: TradingPlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onInventoryClick(InventoryClickEvent event, Player player) {
	final TradingPlayerShopkeeper shopkeeper = this.getShopkeeper();
	event.setCancelled(true);
	final int slot = event.getRawSlot();
	if (slot >= 0 && slot <= 7) {
		// handle changing sell stack size:
		this.handleUpdateItemAmountOnClick(event, 1);
	} else if ((slot >= 9 && slot <= 16) || (slot >= 18 && slot <= 25)) {
		if (shopkeeper.clickedItem != null) {
			// placing item:
			final Inventory inventory = event.getInventory();
			Bukkit.getScheduler().runTaskLater(ShopkeepersPlugin.getInstance(), new Runnable() {
				public void run() {
					inventory.setItem(slot, shopkeeper.clickedItem);
					shopkeeper.clickedItem = null;
				}
			}, 1);
		} else {
			// changing stack size of clicked item:
			this.handleUpdateItemAmountOnClick(event, 0);
		}
	} else if (slot >= 27) {
		// clicking in player inventory:
		if (event.isShiftClick() || !event.isLeftClick()) {
			return;
		}
		ItemStack cursor = event.getCursor();
		if (!Utils.isEmpty(cursor)) {
			return;
		}
		ItemStack current = event.getCurrentItem();
		if (!Utils.isEmpty(current)) {
			shopkeeper.clickedItem = current.clone();
			shopkeeper.clickedItem.setAmount(1);
		}
	} else {
		super.onInventoryClick(event, player);
	}
}
 
Example 11
Source File: GUIListener.java    From EnchantmentsEnhance with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onClick(InventoryClickEvent e) {
    // Handles invalid clicks.
    if (e.getSlot() < 0) {
        return;
    }
    // Handles invalid entity.
    if (!(e.getWhoClicked() instanceof Player)) {
        return;
    }
    // Handles empty slot.
    if (e.getCurrentItem() != null && e.getCurrentItem().getType() == (Material.AIR)) {
        return;
    }
    // Handles non-gui inventory.
    if (e.getRawSlot() > 53) {
        return;
    }

    Player player = (Player) e.getWhoClicked();
    String playerName = player.getName();
    GUIAbstract gui = GUIManager.getMap().get(playerName);
    if (gui != null && gui.getInventory().equals(e.getInventory())) {
        e.setCancelled(true);
        GUIAbstract.GUIAction action = gui.getActions().get(e.getSlot());
        if (action != null) {
            action.click(e.getClick());
            gui.update();
        }
    } else {
        if (isCreatedGUI(e.getInventory())) {
            e.setCancelled(true);
            player.closeInventory();
        }
    }
}
 
Example 12
Source File: InventoryForSingleItem.java    From NBTEditor with GNU General Public License v3.0 5 votes vote down vote up
protected ItemStack getItemToCheck(InventoryClickEvent event) {
	int slot = event.getRawSlot();
	boolean isShift = event.isShiftClick();
	if (isShift && slot > 8 && event.getInventory().firstEmpty() == 4) {
		return event.getCurrentItem();
	} else if (slot == 4 && !isShift && event.getCursor().getType() != Material.AIR) {
		return event.getCursor();
	}
	return null;
}
 
Example 13
Source File: TopTen.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onInventoryClick(InventoryClickEvent event) {
    Inventory inventory = event.getInventory(); // The inventory that was clicked in
    if (inventory.getName() == null) {
        return;
    }
    // The player that clicked the item
    Player player = (Player) event.getWhoClicked();
    if (!inventory.getTitle().equals(plugin.myLocale().topTenGuiTitle)) {
        return;
    }
    event.setCancelled(true);
    player.updateInventory();
    if(event.getCurrentItem() != null && !event.getCurrentItem().getType().equals(Material.AIR) && event.getRawSlot() < 26) {
        event.getCurrentItem().setType(Material.AIR);
        player.closeInventory();
        String playerName = getPlayer(event.getRawSlot());
        UUID uuid = plugin.getPlayers().getUUID(playerName);
        if (uuid != null && plugin.getWarpSignsListener().getWarp(uuid) != null) {
            Util.runCommand(player, "is warp " + playerName);
        }
    }
    if (event.getSlotType().equals(SlotType.OUTSIDE)) {
        player.closeInventory();
        return;
    }
    if (event.getClick().equals(ClickType.SHIFT_RIGHT)) {
        player.closeInventory();
        return;
    }
}
 
Example 14
Source File: NormalPlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onInventoryClick(InventoryClickEvent event, Player player) {
	event.setCancelled(true);
	if (event.getRawSlot() >= 0 && event.getRawSlot() <= 7) {
		// handle changing sell stack size:
		this.handleUpdateItemAmountOnClick(event, 1);
	} else {
		super.onInventoryClick(event, player);
	}
}
 
Example 15
Source File: SchematicsPanel.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Handles when the schematics panel is actually clicked
 * @param event
 */
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClick(InventoryClickEvent event) {
    Player player = (Player) event.getWhoClicked(); // The player that
    // clicked the item
    Inventory inventory = event.getInventory(); // The inventory that was clicked in
    if (inventory.getName() == null) {
        return;
    }
    int slot = event.getRawSlot();
    // Check this is the right panel
    if (!inventory.getName().equals(plugin.myLocale(player.getUniqueId()).schematicsTitle)) {
        return;
    }
    if (slot == -999) {
        player.closeInventory();
        inventory.clear();
        schematicItems.remove(player.getUniqueId());
        event.setCancelled(true);
        return;
    }
    if (event.getClick().equals(ClickType.SHIFT_RIGHT)) {
        event.setCancelled(true);
        player.closeInventory();
        inventory.clear();
        schematicItems.remove(player.getUniqueId());
        player.updateInventory();
        return;
    }
    // Get the list of items for this player
    List<SPItem> thisPanel = schematicItems.get(player.getUniqueId());
    if (thisPanel == null) {
        player.closeInventory();
        inventory.clear();
        schematicItems.remove(player.getUniqueId());
        event.setCancelled(true);
        return;
    }
    if (slot >= 0 && slot < thisPanel.size()) {
        event.setCancelled(true);
        // plugin.getLogger().info("DEBUG: slot is " + slot);
        player.closeInventory(); // Closes the inventory
        inventory.clear();
        // Get the item clicked
        SPItem item = thisPanel.get(slot);
        // Check cost
        if (item.getCost() > 0) {
            if (Settings.useEconomy && VaultHelper.setupEconomy() && !VaultHelper.econ.has(player, item.getCost())) {
                // Too expensive
                Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).minishopYouCannotAfford.replace("[description]", item.getName()));        
            } else {
                // Do something
                if (Settings.useEconomy && VaultHelper.setupEconomy()) {
                    VaultHelper.econ.withdrawPlayer(player, item.getCost());                   
                } 
                Util.runCommand(player, Settings.ISLANDCOMMAND + " make " + item.getHeading());
            }
        } else {
            Util.runCommand(player, Settings.ISLANDCOMMAND + " make " + item.getHeading());
        }
        schematicItems.remove(player.getUniqueId());
        thisPanel.clear();   
    }
    return;
}
 
Example 16
Source File: PlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onInventoryClick(InventoryClickEvent event, final Player player) {
	super.onInventoryClick(event, player);
	final PlayerShopkeeper shopkeeper = this.getShopkeeper();
	int slot = event.getRawSlot();
	if (slot == 2 || slot == 6) {
		ItemStack[] inventory = player.getInventory().getContents();
		ItemStack hireCost = shopkeeper.getHireCost().clone();
		for (int i = 0; i < inventory.length; i++) {
			ItemStack item = inventory[i];
			if (item != null && item.isSimilar(hireCost)) {
				if (item.getAmount() > hireCost.getAmount()) {
					item.setAmount(item.getAmount() - hireCost.getAmount());
					hireCost.setAmount(0);
					break;
				} else if (item.getAmount() == hireCost.getAmount()) {
					inventory[i] = null;
					hireCost.setAmount(0);
					break;
				} else {
					hireCost.setAmount(hireCost.getAmount() - item.getAmount());
					inventory[i] = null;
				}
			}
		}

		if (hireCost.getAmount() == 0) {
			int maxShops = ShopkeepersPlugin.getInstance().getMaxShops(player);

			// call event:
			PlayerShopkeeperHiredEvent hireEvent = new PlayerShopkeeperHiredEvent(player, shopkeeper, maxShops);
			Bukkit.getPluginManager().callEvent(hireEvent);
			if (hireEvent.isCancelled()) {
				// close window for this player:
				this.closeDelayed(player);
				return;
			}

			// check max shops limit:
			maxShops = hireEvent.getMaxShopsForPlayer();
			if (maxShops > 0) {
				int count = ShopkeepersPlugin.getInstance().countShopsOfPlayer(player);
				if (count >= maxShops) {
					Utils.sendMessage(player, Settings.msgTooManyShops);
					this.closeDelayed(player);
					return;
				}
			}

			// hire it:
			player.getInventory().setContents(inventory); // apply inventory changes
			shopkeeper.setForHire(false, null);
			shopkeeper.setOwner(player);
			ShopkeepersPlugin.getInstance().save();
			Utils.sendMessage(player, Settings.msgHired);

			// close all open windows for this shopkeeper:
			shopkeeper.closeAllOpenWindows();
			return;
		} else {
			// not enough money:
			Utils.sendMessage(player, Settings.msgCantHire);
			// close window for this player:
			this.closeDelayed(player);
		}
	}
}
 
Example 17
Source File: CustomItemManager.java    From civcraft with GNU General Public License v2.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST) 
public void OnInventoryClick(InventoryClickEvent event) {
	boolean currentEmpty = (event.getCurrentItem() == null) || (ItemManager.getId(event.getCurrentItem()) == CivData.AIR);
	boolean cursorEmpty = (event.getCursor() == null) || (ItemManager.getId(event.getCursor()) == CivData.AIR);
	
	if (currentEmpty && cursorEmpty) {
		return;
	}
	
	convertLegacyItem(event);
	
	if (event.getRawSlot() < 0) {
		//I guess this means "drop the item?"
		
		//CivLog.debug("GET RAW WAS NEGATIVE, cancel this event it should be invalid.");
		//event.setResult(Result.DENY);
		//event.setCancelled(true);
		
		//try {
		//	Player player = CivGlobal.getPlayer(event.getWhoClicked().getName());
		//	player.updateInventory();
		//} catch (CivException e) {
		//}
		
		return;
	}
	
	InventoryView view = event.getView();
	Inventory clickedInv;
	Inventory otherInv;
	
	if (view.getType().equals(InventoryType.CRAFTING)) {
		//This is the player's own inventory. For some reason it requires
		//special treatment. The 'top' inventory is the 2x2 crafting
		//area plus the output. During shift click, items do not go there
		//so the otherInv should always be the player's inventory aka the bottom.
		if (event.getRawSlot() <= 4) {
			clickedInv = view.getTopInventory();
			otherInv = view.getBottomInventory();
		} else {
			clickedInv = view.getBottomInventory();
			otherInv = view.getBottomInventory();
		}
	} else {
		if (event.getRawSlot() == view.convertSlot(event.getRawSlot())) {
			//Clicked in the top holder
			clickedInv = view.getTopInventory();
			otherInv = view.getBottomInventory();
		} else {
			clickedInv = view.getBottomInventory();
			otherInv = view.getTopInventory();
		}
	}
	
	LoreMaterial current = LoreMaterial.getMaterial(event.getCurrentItem());
	LoreMaterial cursor = LoreMaterial.getMaterial(event.getCursor());
	
	if (event.isShiftClick()) {
		// Shift click is _always_ current item.
	//	CustomItemStack is = new CustomItemStack(event.getCurrentItem());
		if (current != null) {
		//if (is.isCustomItem() && (is.getMaterial() instanceof CustomMaterialExtended)) {
			// Calling onInvShiftClick Event.
			//((CustomMaterialExtended)is.getMaterial()).onInvShiftClick(event, clickedInv, otherInv, is.getItem());
			current.onInvShiftClick(event, clickedInv, otherInv, event.getCurrentItem());
		//}
		}
		
	} else {
		
		if (!currentEmpty && !cursorEmpty) {
			//CustomItemStack currentIs = new CustomItemStack(event.getCurrentItem());
			//CustomItemStack cursorIs = new CustomItemStack(event.getCursor());
			
			if (current != null) {
				current.onInvItemSwap(event, clickedInv, event.getCursor(), event.getCurrentItem());
			}
			
			if (cursor != null) {
				cursor.onInvItemSwap(event, clickedInv, event.getCursor(), event.getCurrentItem());
			}
		} else if (!currentEmpty) {
			// This is a pickup event.
			//CustomItemStack is = new CustomItemStack(event.getCurrentItem());
			if (current != null) {
				// Calling onInvItemPickup Event.
				current.onInvItemPickup(event, clickedInv, event.getCurrentItem());
			}
		} else {
			// Implied !cursorEmpty
			if (cursor != null) {
				// Calling onInvItemDrop Event.
				cursor.onInvItemDrop(event, clickedInv, event.getCursor());
			}
			
		}
	}
}
 
Example 18
Source File: InventoryGui.java    From InventoryGui with MIT License 4 votes vote down vote up
@EventHandler
private void onInventoryClick(InventoryClickEvent event) {
    if (event.getInventory().equals(getInventory(event.getWhoClicked()))) {

        int slot = -1;
        if (event.getRawSlot() < event.getView().getTopInventory().getSize()) {
            slot = event.getRawSlot();
        } else if (event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
            slot = event.getInventory().firstEmpty();
        }
    
        GuiElement.Action action = null;
        GuiElement element = null;
        if (slot >= 0) {
            element = getElement(slot);
            if (element != null) {
                action = element.getAction(event.getWhoClicked());
            }
        } else if (slot == -999) {
            action = outsideAction;
        } else {
            // Click was neither for the top inventory or outside
            // E.g. click is in the bottom inventory
            if (event.getAction() == InventoryAction.COLLECT_TO_CURSOR) {
                simulateCollectToCursor(new GuiElement.Click(gui, slot, null, event.getClick(), event));
            }
            return;
        }
        try {
            if (action == null || action.onClick(new GuiElement.Click(gui, slot, element, event.getClick(), event))) {
                event.setCancelled(true);
                if (event.getWhoClicked() instanceof Player) {
                    ((Player) event.getWhoClicked()).updateInventory();
                }
            }
            if (action != null) {
                // Let's assume something changed and re-draw all currently shown inventories
                for (UUID playerId : inventories.keySet()) {
                    if (!event.getWhoClicked().getUniqueId().equals(playerId)) {
                        Player player = plugin.getServer().getPlayer(playerId);
                        if (player != null) {
                            draw(player);
                        }
                    }
                }
            }
        } catch (Throwable t) {
            event.setCancelled(true);
            if (event.getWhoClicked() instanceof Player) {
                ((Player) event.getWhoClicked()).updateInventory();
            }
            plugin.getLogger().log(Level.SEVERE, "Exception while trying to run action for click on "
                    + (element != null ? element.getClass().getSimpleName() : "empty element")
                    + " in slot " + event.getRawSlot() + " of " + gui.getTitle() + " GUI!");
            t.printStackTrace();
        }
    } else if (hasRealOwner() && owner.equals(event.getInventory().getHolder())) {
        // Click into inventory by same owner but not the inventory of the GUI
        // Assume that the underlying inventory changed and redraw the GUI
        plugin.getServer().getScheduler().runTask(plugin, (Runnable) gui::draw);
    }
}
 
Example 19
Source File: NewItemShop.java    From BedwarsRel with GNU General Public License v3.0 4 votes vote down vote up
private void handleCategoryInventoryClick(InventoryClickEvent ice, Game game, Player player) {

    int catSize = this.getCategoriesSize(player);
    int sizeCategories = this.getInventorySize(catSize) + 9;
    int rawSlot = ice.getRawSlot();

    if (rawSlot >= this.getInventorySize(catSize) && rawSlot < sizeCategories) {
      ice.setCancelled(true);
      if (ice.getCurrentItem().getType() == Material.SLIME_BALL) {
        this.changeToOldShop(game, player);
        return;
      }

      if (ice.getCurrentItem().getType() == Material.BUCKET) {
        game.getPlayerSettings(player).setOneStackPerShift(false);
        player.playSound(player.getLocation(), SoundMachine.get("CLICK", "UI_BUTTON_CLICK"),
            Float.valueOf("1.0"), Float.valueOf("1.0"));
        this.openCategoryInventory(player);
        return;
      } else if (ice.getCurrentItem().getType() == Material.LAVA_BUCKET) {
        game.getPlayerSettings(player).setOneStackPerShift(true);
        player.playSound(player.getLocation(), SoundMachine.get("CLICK", "UI_BUTTON_CLICK"),
            Float.valueOf("1.0"), Float.valueOf("1.0"));
        this.openCategoryInventory(player);
        return;
      }

    }

    if (rawSlot >= sizeCategories) {
      if (ice.isShiftClick()) {
        ice.setCancelled(true);
        return;
      }

      ice.setCancelled(false);
      return;
    }

    MerchantCategory clickedCategory = this.getCategoryByMaterial(ice.getCurrentItem().getType());
    if (clickedCategory == null) {
      if (ice.isShiftClick()) {
        ice.setCancelled(true);
        return;
      }

      ice.setCancelled(false);
      return;
    }

    this.openBuyInventory(clickedCategory, player, game);
  }
 
Example 20
Source File: TradeInventoryListener.java    From civcraft with GNU General Public License v2.0 4 votes vote down vote up
public void handleShiftClick(InventoryClickEvent event, Player player, TradeInventoryPair pair) {
	/* First determine if we're shifting into our inv or into the trade window. */
	if (event.getRawSlot() > SLOTS_END) {
		/* We're clicking in our inventory, trying to bring in an item. 
		 * lets cheat by creating a new temp inventory which contains the
		 * current contents of our slots, add this item to it, then replace
		 * the slots with that inv's contents. 
		 */
		Inventory tempInv = Bukkit.createInventory(event.getWhoClicked(), 9);
		/* Copy contents from current slots. */
		int k = 0;
		for (int i = MY_SLOTS_START; i < MY_SLOTS_END; i++) {
			tempInv.setItem(k, event.getInventory().getItem(i));;
			k++;
		}
		
		/* Add this item to our tempInv. */
		HashMap<Integer, ItemStack> leftovers = tempInv.addItem(event.getCurrentItem());
		
		/* Copy contents of the temp inventory on top of our slots. */
		k = 0;
		for (int i = MY_SLOTS_START; i < MY_SLOTS_END; i++) {
			event.getInventory().setItem(i, tempInv.getItem(k));
			k++;
		}
		
		/* Now, remove the item from the player's inventory. */
		player.getInventory().setItem(event.getSlot(), null);
		
		/* Re-add any leftovers we might have. */
		for (ItemStack stack : leftovers.values()) {
			player.getInventory().addItem(stack);
		}
		
		/* Cancel normal event processing. */
		TaskMaster.syncTask(new SyncInventoryChangeAll(pair.inv, pair.otherResident, pair.otherInv));				
		event.setCancelled(true);
		return;
	} else {
		/* We're clicking in the trade inventory, tryign to take out an item. */
		if (event.getRawSlot() < OTHERS_SLOTS_END) {
			/* We tried to shift click on the other player's side. Cancel. */
			event.setCancelled(true);
			return;
		} else {
			/* We're clicking on our side, allow it as normal. */
			TaskMaster.syncTask(new SyncInventoryChangeAll(pair.inv, pair.otherResident, pair.otherInv));		
			return;
		}
	}
}