最小代码示例:
public class HelloApplication extends Application implements EventHandler<HelloApplication.MyEvent> {
public class MyEvent extends Event {
public static final EventType TYPE = new EventType<>(Event.ANY, "MyType");
public MyEvent() {
super(TYPE);
}
}
@Override
public void handle(MyEvent myEvent) {
System.out.println("Event handled!");
}
@Override
public void start(Stage stage) throws IOException {
BorderPane root = new BorderPane();
stage.setScene(new Scene(root, 640, 480));
Button button1 = new Button("Click");
button1.setOnAction(event -> {
button1.fireEvent(new MyEvent());
System.out.println("Event fired!");
});
root.setTop(button1);
Button button2 = new Button("Clack");
button2.addEventHandler(MyEvent.TYPE, this);
root.setBottom(button2);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
我收到“事件被解雇!”在我的控制台中,但不是“事件已处理!”。
当我将事件监听器添加到button1时,它就起作用了。我错过了一些明显的东西吗?是否不可能在 A 上触发事件并在 B 上监听它?
代码
button2.addEventHandler(MyEvent.TYPE, this);
将当前
HelloApplication
实例 (this
) 注册为 button2
的事件处理程序。这意味着每当 button2
触发事件类型为 MyEvent.TYPE
的事件时,都会调用 this.handle(...)
。
但是,在您发布的代码中,
button2
永远不会触发此类事件。该事件唯一被触发的时间是通过代码
button1.fireEvent(new MyEvent());
这当然会导致
button1
触发事件,而不是 button2
。