简体   繁体   中英

Problems with accessing HashMaps from other classes

I am writing a plugin using Spigot (pretty much Bukkit) but I'm having problems accessing a HashMap from one class in another. Here is my HashMap and getter:

private Map<String, Integer> compPlayers = new HashMap<String, Integer>();

public Map<String, Integer> getCompPlayers(){
    return compPlayers;
}

I am able to see if the HashMap contains certain keys from within the class such as here:

if(args[0].equalsIgnoreCase("join")){
    if(compPlayers.containsKey(p.getName())){
        p.sendMessage(ChatColor.RED + "You are already part of the competition");
        return false;
    }

yet in my listener class, I can't seem to access it properly. Here's a section of code in my listener class:

public class CompetitionListener implements Listener {

private PluginMain plugin;

public CompetitionListener(PluginMain plugin){
    this.plugin = plugin;
}

@EventHandler
public void onBlockPlace(BlockBreakEvent e){
        Player p = (Player) e.getPlayer();
        p.sendMessage("BlockBreakEvent");
        if(plugin.getCommands().getCompPlayers().containsKey(p.getName())){
            p.sendMessage(ChatColor.YELLOW + "You scored a point!");
            plugin.getCommands().getCompPlayers().put(p.getName(), plugin.getCommands().getCompPlayers().get(p.getName() + 1));
        }
    }
}

PluginMain is the class that extends JavaPlugin and getCommands() is a getter for the Commands class from within it.

Though I am able to access all these methods from the listener class without errors, the line checking if the player name is in the HashMap doesn't work and always returns false. The event itself does work.

You never register the events in your Listener class.

In your Listener class's constructor, add the following:

plugin.getServer().getPluginManager().registerEvents(this, plugin);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM