Inventory ClickEvent not working - java

When I click the Item in the Inventory, it simply does nothing and I can drag it anywhere I want. Then I re-open the inventory and the Item is back. I want the item a click (The Notify item in this case) to toggle the notify boolean and close the Inventory. Please help. It may be a stupid solution but sometimes the simple stuff can escape me. Thanks.
This is the Inventory:
public class GUI extends JavaPlugin implements Listener
{
private API api;
AlphaCommand command = new AlphaCommand();
public static Inventory inv = Bukkit.createInventory(null, 9, ChatColor.AQUA + "Alpha Config");
public static boolean isNotifyEnabled()
{
return AlphaCommand.notify;
}
protected String getCheckName()
{
return this.getCheckName();
}
public static void openGUI(Player player, Inventory inv)
{
ItemStack checks = new ItemStack(Material.DIAMOND_SWORD);
ItemStack banPlayer = new ItemStack(Material.GOLD_AXE);
ItemStack autoBan = new ItemStack(Material.DIAMOND_AXE);
ItemStack notify = new ItemStack(Material.SLIME_BALL);
ItemMeta checksMeta = checks.getItemMeta();
ItemMeta autoBanMeta = autoBan.getItemMeta();
ItemMeta notifyMeta = notify.getItemMeta();
ItemMeta banPlayerMeta = banPlayer.getItemMeta();
checksMeta.setDisplayName(ChatColor.BLUE + "Checks");
autoBanMeta.setDisplayName(ChatColor.BLUE + "AutoBan");
notifyMeta.setDisplayName(ChatColor.BLUE + "Notify");
banPlayerMeta.setDisplayName(ChatColor.BLUE + "Ban Player");
checks.setItemMeta(checksMeta);
autoBan.setItemMeta(autoBanMeta);
notify.setItemMeta(notifyMeta);
banPlayer.setItemMeta(banPlayerMeta);
inv.setItem(7, banPlayer);
inv.setItem(1, checks);
inv.setItem(3, autoBan);
inv.setItem(5, notify);
player.openInventory(inv);
}
public static void open(Player player, Inventory inv)
{
if(player instanceof Player)
{
player.openInventory(inv);
}
}
public static Inventory getGUI(){
return inv;
}
#EventHandler
public void onInventoryClick(InventoryClickEvent e)
{
Bukkit.getPluginManager().registerEvents(this, Bukkit.getPluginManager().getPlugins()[0]);
String invName = ChatColor.stripColor(e.getClickedInventory().getName());
Player player = (Player) e.getWhoClicked(); // The player that clicked the item
ItemStack clicked = e.getCurrentItem(); // The item that was clicked
#SuppressWarnings("unused")
Inventory inventory = e.getInventory(); // The inventory that was clicked in
if(invName.equalsIgnoreCase(inv.getName()))
{
if((clicked == null) || (clicked.getType() == Material.AIR) || (!clicked.hasItemMeta()))
{
player.closeInventory();
return;
}
if(clicked.getItemMeta().getDisplayName().equalsIgnoreCase("AutoBan"))
{
Configuration config = this.api.getConfiguration();
boolean autoBan = config.readBoolean("checks." + getCheckName() + ".AutoBan");
if (config.readBoolean("checks." + getCheckName() + ".AutoBan") == true)
{
autoBan = false;
e.setCancelled(true);
player.closeInventory();
return;
}
else if(autoBan == false)
{
autoBan = true;
e.setCancelled(true);
player.closeInventory();
return;
}
else
{
e.setCancelled(true);
player.closeInventory();
return;
}
}
if(clicked.getItemMeta().getDisplayName().equalsIgnoreCase("Notify"))
{
boolean notify = isNotifyEnabled();
if(notify == true)
{
notify = false;
e.setCancelled(true);
player.closeInventory();
return;
}
else if(notify == false)
{
notify = true;
e.setCancelled(true);
player.closeInventory();
return;
}
}
if(clicked.getItemMeta().getDisplayName().equalsIgnoreCase("Checks"))
{
player.sendMessage(ChatColor.RED + "This Feature is coming soon to Alpha.");
e.setCancelled(true);
player.closeInventory();
return;
}
if(e.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase("Ban Player"))
{
player.sendMessage("This Feature is coming soon to Alpha V.4");
e.setCancelled(true);
player.closeInventory();
return;
}else
{
player.closeInventory();
e.setCancelled(true);
return;
}
}
}
}

There seems to be multiple issues in the code that you have provided above that will cause the expected result to not be seen.
#1
Firstly you register the events for this class, inside the event itself, which means it'll never get registered unless the event get's called, which will never happen unless you register it... See the problem? So what you need to do is move the following line of code into your onEnable method.
Bukkit.getPluginManager().registerEvents(this, Bukkit.getPluginManager().getPlugins()[0]);
You need to make a few changes to this line of code. You need to replace this with a new instance of the listener object, new GUI(). It's also recommended that you register the listener with the plugin that your calling it from, but fortunately, if you put this in your onEnable, your onEnable method is inside your plugin class. This means that you can change your plugin to this. You new line of code will look like this.
Bukkit.getPluginManager().registerEvents(new GUI(), this);
Put that in your onEnable and that issue here should be resolved.
#2
The second issue is that when you're checking your item names and you're not stripping colour. This get's rid of an colours in the string. This is because your item names are ChatColor.BLUE + "AutoBan" however you're checking if it equals "AutoBan" which is different. All you need to do to fix this issue is exactly the same with what you did with the inventory name, and use ChatColor.stripColor(itemName) to get a string you can check against.
For example:
String itemName = ChatColor.stripColor(clicked.getItemMeta().getDisplayName());
if (itemName.equals("AutoBan")){
Note: I also replaced equalsIgnoreCase with equals as the cases always matched, so was an unnecessary check.

Related

How do I perform an action only on the even something is removed from an array list?

Here is an example of what I'm working with...
Player p = (Player) sender;
ArrayList<Player> nofalldmg = new ArrayList<Player>();
if (p.hasPermission("custome.fly")) {
if (p.isFlying()) {
p.setAllowFlight(false);
p.setFlying(false);
nofalldmg.add(p);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
nofalldmg.remove(p);
}
}, 60);
So as you can see I have two lines of code 1 "nofalldmg.add(p);" that adds the player to an array list, and 2 "nofalldmg.remove(p);" that removes the player from the array list
When they are added to the array list their fall damage is canceled, what I want to know is once they are removed from that array list how do I re enable their fall damage?
This is the full class that can help you (without import, with comment to explain how it works) :
private final ArrayList<Player> nofalldmg = new ArrayList<Player>(); // declare list
#EventHandler
public void onDamageDisabler(EntityDamageEvent e) { // method to disable fall damage
if (e.getCause() == EntityDamageEvent.DamageCause.FALL) { // only if it's fall
if(e.getEntity() instanceof Player && nofalldmg.contains((Player) e.getEntity()) { // only if it's in list
e.setCancelled(true); // cancel
}
}
}
public void yourMethod(CommandSender sender) {
Player p = (Player) sender;
if (p.hasPermission("custome.fly")) { // your conditions
if (p.isFlying()) {
p.setAllowFlight(false);
p.setFlying(false);
nofalldmg.add(p); // here we add it to the list
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
nofalldmg.remove(p);
// here you can resetting everything that you want
}, 60); // no we remove it, so can take damage
}
}
}

Healing/Damage Blocks are outputting twice?

#EventHandler
public void playerInteraction(PlayerInteractEvent event)
{
Action action = event.getAction();
Player player = event.getPlayer();
Block block = event.getClickedBlock();
if (action.equals(Action.RIGHT_CLICK_BLOCK))
{
if (block.getType().equals(Material.NETHER_WART_BLOCK))
{
player.setHealth(player.getHealth() -1);
player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_HURT, 10, 1);
}
else if (block.getType().equals(Material.DIAMOND_BLOCK))
{
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 1000, 2));
player.playSound(player.getLocation(), Sound.ENTITY_SPLASH_POTION_BREAK, 10, 1);
}
else if(block.getType().equals(Material.EMERALD_BLOCK))
{
if (player.getHealth() != 20)
{
player.setHealth(player.getHealth() + 1);
player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 10, 1);;
}
if (player.getHealth() == 20)
{
player.sendMessage(ChatColor.DARK_RED + "You are already at full health!");
}
}
}
}
For some reason, all of these things happen twice whenever I right click the designated blocks. Anyone know why? I have posted the entire method, it's a player interaction event.
Thanks :)
First of all, make sure yo haven't registered the Listener class containing the event handler twice.
If that's not the case, according to this thread on the spigot forums, since Mojang added the left hand slot to Minecraft some events like PlayerInteractEvent or InventoryClickEvent will be called twice (once for each hand).
One possible fix is to "disable" the left hand on the event handler:
#EventHandler
public void onPlayerInteraction(PlayerInteractEvent event) {
if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getHand() == EquipmentSlot.HAND) {
//Do something once
}
}
If you require that both hands could be used to trigger the event you could do the following:
First time the code gets executed you add the player to a list.
Before executing the code you check if the player is in the list. If it's in the list it means the code was executed once so you can skip it.
Schedule a task to remove the player from the list some ticks later.
The code could be as follows:
public class Foo implements Listener {
//An instance of the main plugin class
private MainClass plugin;
private List<UUID> playerBlacklist = new ArrayList<>();
#EventHandler
public void onPlayerInteractEvent(PlayerInteractEvent event) {
if(playerBlacklist.contains(event.getPlayer().getUniqueId)) {
return;
} else {
blacklistPlayer(event.getPlayer());
}
//Do something
}
private void blacklistPlayer(UUID uuid) {
playerBlacklist.add(uuid);
BukkitRunnable runnable = new BukkitRunnable(){
#Override
public void run() {
playerBlacklist.remove(uuid);
}
}
runnable.runTaskLaterAsynchronously(plugin, 5L);
}
}
Let me know if this solved your issue.

How to leave in-app-billing-purchase within a class

I already have in my application the integration with "in-app-billing-purchase" however I have several activity where I need to be duplicating all the code.
So I thought about leaving everything focused on a single class, I wastancio the class and I arrive if the item was bought.
Just that I have a big problem the "in-app-billing-purchase" uses Listener OnIabPurchaseFinishedListener and QueryInventoryFinishedListener
How can I leave all this organized in a single class and just check with a simple call in my activity?
Calling code:
Billing bl = new Billing(getActivity().getApplicationContext());
if (bl.Comprado())
Toast.makeText(getActivity(), "Comprado", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getActivity(), "Erro comprado", Toast.LENGTH_SHORT).show();
Class I created to be called multiple times
public class Billing {
// Item name for premium status
private static final String SKU_PREMIUM = "premium";
// private static final String SKU_PREMIUM = "tirarbanner";
// Flag set to true when we have premium status
private static boolean mIsPremium = false;
// In-app Billing helper
private IabHelper mAbHelper;
public Billing(Context context) {
String base64EncodedPublicKey = "xxx";
// Create in-app billing helper
mAbHelper = new IabHelper(context, base64EncodedPublicKey);
// and start setup. If setup is successfull, query inventory we already
// own
mAbHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
return;
}
mAbHelper.queryInventoryAsync(mGotInventoryListener);
}
});
}
public static boolean Comprado() {
return mIsPremium;
}
/**
* Listener that is called when we finish purchase flow.
*/
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
return;
}
// Purchase was successfull, set premium flag and update interface
if (purchase.getSku().equals(SKU_PREMIUM)) {
mIsPremium = true;
}
}
};
/**
* Listener that's called when we finish querying the items and
* subscriptions we own
*/
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
// Have we been disposed of in the meantime? If so, quit.
if (mAbHelper == null)
return;
// Is it a failure?
if (result.isFailure()) {
return;
}
// Do we have the premium upgrade?
Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM);
mIsPremium = premiumPurchase != null;
}
};
}
There's already a library for that.
Check android-inapp-billing-v3.

How to check if a player right-clicked another player

Looking for the right event to work with. I want to check if a player right-clicked another player.
This is what i have so far (doesn't work. Not getting into the if or the else statement:
public void onPlayerRightClicks(PlayerInteractEntityEvent e) {
Player p=e.getPlayer();
if(e.getRightClicked() instanceof Player) p.sendMessage("You have rightclicked a player.");
else p.sendMessage("You didn't hit anyone with your spell");
}
Found the answer to the question by combining my own code with codes from another answer on a similar question:
#SuppressWarnings("deprecation")
#EventHandler
public void onPlayerClick(PlayerInteractEvent e) {
Player p=e.getPlayer();
NBTItem item = new NBTItem(p.getItemInHand());
Entity en=getNearestEntityInSight(p,5);
if(e.getAction()==Action.RIGHT_CLICK_AIR && en instanceof Player) p.sendMessage("You have rightclicked a player.");
else p.sendMessage("You didn't hit anyone with your spell");
}
public static Entity getNearestEntityInSight(Player player, int range) {
ArrayList<Entity> entities = (ArrayList<Entity>) player.getNearbyEntities(range, range, range);
ArrayList<Block> sightBlock = (ArrayList<Block>) player.getLineOfSight(null, range);
ArrayList<Location> sight = new ArrayList<Location>();
for (int i = 0;i<sightBlock.size();i++)
sight.add(sightBlock.get(i).getLocation());
for (int i = 0;i<sight.size();i++) {
for (int k = 0;k<entities.size();k++) {
if (Math.abs(entities.get(k).getLocation().getX()-sight.get(i).getX())<1.3) {
if (Math.abs(entities.get(k).getLocation().getY()-sight.get(i).getY())<1.5) {
if (Math.abs(entities.get(k).getLocation().getZ()-sight.get(i).getZ())<1.3) {
return entities.get(k);
}
}
}
}
}
return null;
}
Even though it works, i don't think it's an optimal answer, as there should be an event that can check whether or not a player rightclicked or at least leftclicked another player. The getNearestEntitySight method finds the closest entity in the player's sight. I combined it with my code which runs when a player rightclicks, using the PlayerInteractEvent.
Try this:
#EventHandler
public void onPlayerInteractEntity(final PlayerInteractAtEntityEvent e) {
final Player p = e.getPlayer();
if (e.getRightClicked() instanceof Player) {
final Player clicked = (Player) e.getRightClicked();
// DO STUFF
}
}

Minecraft bukkit plugin right click item

I am making a plugin for a server I am developer on and I was developing a plugin!
I wanted to do commands to spawn a boss egg in by doing /boss give lvl <lvl> slime after you did the command it would give you an item that you can right click to spawn the boss in! Well like all new developers stuff doesn't always go the way you think it does. Here's my code I put in for checking if a player right click air or a block with the item SLIME_BALL in the players hand.
#EventHandler
public void onPlayerClicks(PlayerInteractEvent event) {
Player player = event.getPlayer();
Action action = event.getAction();
if (action.equals(Action.RIGHT_CLICK_AIR) || action.equals(Action.RIGHT_CLICK_BLOCK)) {
if (player.getItemInHand().getType() == Material.SLIME_BALL) {
player.sendMessage("You have right click a slime ball!");
}
}
}
Given that you are not seeing any stack traces in your logs, I would concur that your event listener is not registered. Let's say your listener class is called MyEventHandler it would be registered in onEnable() method, something similar to this
class MyPlugin extends JavaPlugin {
...
public void onEnable() {
Listener myEvtHnd = new MyEventHandler();
Bukkit.getPluginManager().registerEvents( myEvtHnd, this );
...
}
}
In general, your handler looks appropriate. PlayerInteractEvent provides a convenience method getItem() that returns the player's current item-in-hand. However, regardless of which method is used, you must check that the ItemStack returned is not null, which will happen if the player has no item in-hand.
#EventHandler
public void onPlayerClicks(PlayerInteractEvent event) {
Player player = event.getPlayer();
Action action = event.getAction();
ItemStack item = event.getItem();
if ( action.equals( Action.RIGHT_CLICK_AIR ) || action.equals( Action.RIGHT_CLICK_BLOCK ) ) {
if ( item != null && item.getType() == Material.SLIME_BALL ) {
player.sendMessage( "You have right click a slime ball!" );
}
}
}
Maybe instead of action.equals(), you can use action ==, as in:
if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) {
if (player.getItemInHand().getType() == Material.SLIME_BALL) {
player.sendMessage("You have right click a slime ball!");
}
}

Categories

Resources