为了测试我对Java接口的理解,我将按钮单击事件处理程序中的匿名类拉到了一个单独的类中-该类起作用了,但是我不了解它为什么起作用。
我原本希望自己必须调用类的handle()
方法,但似乎需要将EventHandler实现作为参数传递。单击按钮显然是在调用handle()
方法,但我不清楚为什么。
匿名类版本
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnaction(new EventHandler<actionEvent>() {
@Override
public void handle(actionEvent event) {
System.out.println("Hello World!");
}
});
单独的班级版本
public class HelloWorldEventHandler implements EventHandler<actionEvent> {
public void handle(actionEvent event) {
System.out.println("Hello World!");
}
}
btn.setText("Say 'Hello World'");
HelloWorldEventHandler handler = new HelloWorldEventHandler();
btn.setOnaction(handler);