简体   繁体   English

如何从另一个 class I Java 访问变量

[英]How can I acces variable from another class I Java

I made minecraft plugin which have afk function but I need when player left and is in AFK list remove them!我制作了具有 afk function 的 minecraft 插件,但是当玩家离开并且在 AFK 列表中时我需要删除它们! So I made this所以我做了这个

MyClass instance = new MyClass();

// Im getting the table like this

instance.MyTable

Which dont works because I have already and quit event that just set custom quit messsage so it is weird哪个不起作用,因为我已经退出事件,只是设置了自定义退出消息,所以很奇怪

So my code looks like this!所以我的代码看起来像这样!

public class QuitEvent implements Listener{
    
    afkCommand instance = new afkCommand();
    
    @EventHandler
    public void onQuit(PlayerQuitEvent event) {
        Player player = event.getPlayer();
        
        event.setQuitMessage("");
        Bukkit.broadcastMessage(ChatColor.WHITE + "[" + ChatColor.RED + "-" + ChatColor.WHITE + "] " + ChatColor.YELLOW + player.getDisplayName() + " has disconnected!");
        if (instance.AFK_Players.contains(event.getPlayer().getDisplayName())) {
            instance.AFK_Players.remove(event.getPlayer().getDisplayName());
            Bukkit.getConsoleSender().sendMessage("[Pixeluted Surival] " + event.getPlayer().getDisplayName() + " has been removed from AFK list because of quit!");
        }
    }
}

Also please correct me if Im wrong using this forum Im new to here!如果我使用这个论坛有误,也请纠正我我是新来的! Thanks!谢谢!

Well i don't know what your MyClass looks like or your MyTable .好吧,我不知道您的MyClass是什么样子或您的MyTable Judging off of first glance,First you need to add event handler within your constuctor to each object or item using it by creating an instance of listener eg乍一看,首先你需要在你的构造函数中添加事件处理程序到每个 object 或通过创建一个监听器实例来使用它的项目,例如

 QuitEvent handler = new QuitEvent(); object.addListener(handler);

Then add the first code snippet you sent in your main class method.然后添加您在主 class 方法中发送的第一个代码片段。 Plus i don't know if you are implementing actionlistener or listener but which ever the case make sure to import the classes you are implementing into your constructor class.另外,我不知道您是在实现actionlistener还是listener ,但无论哪种情况,请确保将您正在实现的类导入构造函数 class。

I fixed it by setting the variable to static and used diffrent type of accesing it!我通过将变量设置为 static 来修复它并使用不同类型的访问它! Thanks for all responds!感谢大家的回复!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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