[英]Enabling Listener on bukkit
package me.TimewalkerZ.Broadcastoncommand;
import java.util.List;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import net.minecraft.server.v1_8_R1.*;
public class Broadcastoncommand extends JavaPlugin implements Listener {
public final Logger logger = Logger.getLogger("Minecraft");
public static Broadcastoncommand plugin;
@Override
public void onDisable() {
PluginDescriptionFile pdfFile = this.getDescription();
this.logger.info(pdfFile.getName() + " Has been Disabled!");
}
@Override
public void onEnable() {
PluginDescriptionFile pdfFile = this.getDescription();
this.logger.info(pdfFile.getName() + " Version " + pdfFile.getVersion() + " Has been Enabled!");
getConfig().options().copyDefaults(true);
saveConfig();
}
@EventHandler
public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) {
Player p = event.getPlayer();
if(!p.hasPermission("Broadcastoncommand.silent")) {
List<String> cmds = plugin.getConfig().getStringList("CommandsBC");
for (String command : cmds) {
if(event.getMessage().toLowerCase().startsWith("/" + command)) {
p.sendMessage("§6" + p + "§6 just did the command " + command + "§6 join them if you have the command unlocked.");
}
}
}
}
你好,我试过运行这个,但它似乎根本不起作用。 我的意思是它编译和运行没有错误,但它在游戏中没有做任何事情。 顺便说一下,这个插件的目的是在有人使用配置中的命令时进行广播。
在您的onEnable
方法中添加这一行:
getServer().getPluginManager().registerEvents(this, this);
第一个this
参数是要为其注册事件的插件,第二个this
参数是插件的侦听器。
与此同时,由于“插件”而引发 NullPointerException。 这将返回 null,因为plugin
未设置为任何内容。 相反,使用这个
List<String> cmds = this.getConfig().getStringList("CommandsBC");
另一种实现此目的但保持单例模式的方法是在启动时将插件实例分配给plugin
,方法是在onEnable
添加以下行:
plugin = this;
要注册您的活动,您需要添加:
Bukkit.getPluginManager().registerEvents(this, this);
this
侦听器注册到this
由于以下任一原因,您还会收到NullPointerException
:
plugin
为空,最终你可以删除plugin.
因为它是您的主类,而getConfig()
是父类中的一个方法。 2.) getConfig()
返回 null,因为 fil 不存在或未生成。 您需要将config.yml
添加到您项目中的src
文件夹中,此后,如果文件不存在,则需要在插件启用时使用saveDefaultConfig()
方法生成它。 例如:
try { File config = new File(getDataFolder(), "config.yml"); if(!getDataFolder().exists())getDataFolder().mkdirs(); if(!config.exists())saveDefaultConfig(); } catch (Exception e) { e.printStackTrace(); }
3.) config 中指定的路径不存在。 记住路径区分大小写。 getConfig().getStringList("CommandsBC")
可能由于列表为空或路径不存在而返回 null(请记住它区分大小写)。
这些选项可能会导致您的NullPointerException
,如果您需要更多信息,请发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.