Solved Removing an ItemStack from your Cursor

Discussion in 'Plugin Development' started by WiseHollow, Jan 9, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    WiseHollow

    I am listening to an InventoryClickEvent and when certain conditions are met, I want to get rid of the item that is being held with the cursor. Is this possible?
     
  2. Try setting the item air ..
    Code:java
    1.  
    2. new ItemStack(Material.AIR)
    3.  
     
  3. Offline

    WiseHollow

    @MaTaMoR_ No success.
     
  4. Offline

    nverdier

  5. Offline

    1Rogue

    I have a method that would be helpful here:

    Code:java
    1. /**
    2.  * Returns the inventory slot for the item in a Player's hand.
    3.  *
    4.  * @since 0.1.0
    5.  * @version 0.1.0
    6.  *
    7.  * @throws IllegalStateException if the item is modified during the method
    8.  * @param p The player to get the item slot from
    9.  * @return The non-raw slot number of the item being held
    10.  */
    11. public static synchronized int getHeldItemSlot(Player p) {
    12. byte[] b = new byte[32];
    13. new Random().nextBytes(b);
    14. List<String> bitStr = new ArrayList<>(Arrays.asList(Base64.encode(b)));
    15. ItemStack[] contents = p.getInventory().getContents();
    16. //Time is of the essence now
    17. List<String> oldLore = p.getItemInHand().getItemMeta().getLore();
    18. p.getItemInHand().getItemMeta().setLore(bitStr);
    19. for (int w = 0; w < 9; w++) {
    20. if (contents[w].getItemMeta().getLore().equals(bitStr)) {
    21. p.getItemInHand().getItemMeta().setLore(oldLore);
    22. return w;
    23. }
    24. }
    25. p.getItemInHand().getItemMeta().setLore(oldLore);
    26. throw new IllegalStateException("Race conflict with other plugin while running method!");
    27. }


    Essentially with the implementation of this you can do:

    Code:java
    1. @EventHandler
    2. public void onClick(InventoryClickEvent event) {
    3. //other code...
    4. //Presuming the below is already checked or done, do this on your own
    5. Player p = (Player) event.getWhoClicked();
    6. if (p.getItemInHand() != null) {
    7. p.getInventory().setItem(InventoryUtil.getHeldItemSlot(p), null); //InventoryUtil is the class I use for my method
    8. }
    9. }


    Note that a race condition can occur doing this, so you should be care to note that an IllegalStateException will be thrown if this occurs (very rare). If you want you can handle the error or change my method for your use and instead of throwing the error you can just call the method again:

    Code:java
    1. return InventoryUtil.getHeldItemSlot(p);


    Which will make it a factor of n^n times more unlikely to happen (i.e. impossible).
     
    Last edited: Jan 11, 2015
    WiseHollow likes this.
Thread Status:
Not open for further replies.

Share This Page