Run command on click of item in GUI

Discussion in 'Plugin Development' started by glasseater, Dec 26, 2014.

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

    glasseater

    Hello Bukkit,

    I am wondering today, how I can run the command "/buy blah blah blah " when a player clicks an item in my gui. I have tried
    Code:
    Bukkit.dispatchCommand(player, "command")
    But that did not work this is what part of my gui code looks like:
    Code:
        @EventHandler
        public void onInventoryClick(InventoryClickEvent e) {
            if (!e.getInventory().getName().equalsIgnoreCase(GUI.getName())) return;
            if (e.getCurrentItem().getItemMeta() == null) return;
            if (e.getCurrentItem().getItemMeta().getDisplayName().contains("FLASHBANG")) { /*Stun Grenade (adds blindness and confusion)*/
                e.setCancelled(true);
                ItemStack ball = new ItemStack(Material.SNOW_BALL, 3);
                e.getWhoClicked().getInventory().addItem(ball);
                e.getWhoClicked().closeInventory();
    Any help is much appreciated
     
  2. Offline

    fireblast709

    @glasseater What exactly didn't work? That aside:
    • Check if getCurrentItem() doesn't return null.
    • Instead of checking if getItemMeta() == null, check if !hasItemMeta(). (It's a bit cleaner, and a bit faster as it isn't forced to create ItemMeta objects when it doesn't need them)
    • You forgot to check if ItemMeta hasDisplayName().
    • Never close the Inventory in the InventoryClickEvent, schedule a task that does that for you (see the documentation). Note that it doesn't have to be delayed:
      Code:Java
      1. new BukkitRunnable()
      2. {
      3. ...
      4. }.runTask(pluginInstance);
     
  3. Offline

    javipepe

    You could just use this;

    Code:
    Player p = e.getPlayer();
    p.performCommand("command here (without the /)");
     
  4. Offline

    glasseater

    @javipepe
    That doesn't work. The gui will not function correctly, on the click of snowball.
     
  5. Offline

    teej107

  6. Offline

    DemKazoo

    If the clickeditem eaquls a snowball, then launch command.


    Code:
    if(e.getClickedItem().getType() == Material.SNOWBALL());
    p.performCommand("cmd");
    p.closeInventory();
    <Edited by bwcfwalshy: I seem like I am always editing you, anyhow fixed bracket.>
     
    Last edited by a moderator: Dec 26, 2014
Thread Status:
Not open for further replies.

Share This Page