创建自定义事件
有时你需要创建自己的事件,其他插件可以监听(Vault,其他插件,这样做),甚至取消。Bukkit 的 Event API 允许这样做。你需要做的就是创建一个新类,让它扩展 Event
,添加处理程序和你的事件所需的属性(如播放器或消息)。
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public final class CustomEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private String message;
public CustomEvent(String example) {
message = example;
}
public String getMessage() {
return message;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
致电你的自定义活动
你可以控制创建和调用你的事件,你可以在其中调用它完全取决于你。这是一个例子
// Create the event here
CustomEvent event = new CustomEvent("Sample Message");
// Call the event
Bukkit.getServer().getPluginManager().callEvent(event);
Bukkit.getServer().broadcastMessage(event.getMessage());
记住:你控制着自己的事件。如果你不调用它,并采取行动,它就不会发生!
听自定义事件
收听自定义事件与收听正常事件相同。
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
public final class CustomListener implements Listener {
@EventHandler
public void onCustomEvent(CustomEvent event) {
// Some code here
}
}
使你的 CustomEvent 可以取消
如果你想让你的活动取消,只需添加 implements Cancellable
,boolean cancelled
和一个 getter 和 setter:
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Cancellable;
public final class CustomEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private String message;
private boolean cancelled;
public CustomEvent(String example) {
message = example;
}
public String getMessage() {
return message;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancel) {
cancelled = cancel;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
之后,你将检查插件是否已取消自定义事件。
// Create the event here
CustomEvent event = new CustomEvent("Sample Message");
// Call the event
Bukkit.getServer().getPluginManager().callEvent(event);
// Check if the event is not cancelled
if (!event.isCancelled()) {
Bukkit.getServer().broadcastMessage(event.getMessage());
}