gpt4 book ai didi

java - 按下按钮时如何自动调用 EventHandler

转载 作者:行者123 更新时间:2023-12-02 09:20:49 24 4
gpt4 key购买 nike

为了测试我对 Java 接口(interface)的理解,我将按钮单击事件处理程序中的匿名类拉到一个单独的类中 - 这已经起作用了 - 但我不明白它为什么起作用。

我原以为必须自己调用类的 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);

最佳答案

这是 part of the JavaFX Button definition 。查看 setOnAction()onActionProperty()

onActionProperty() 方法返回您提供的 EventHandler 的包装版本。它将返回的对象描述为:

The button's action, which is invoked whenever the button is fired. This may be due to the user clicking on the button with the mouse, or by a touch event, or by a key press, or if the developer programmatically invokes the fire() method.

也就是说,当您setOnAction()时,只要按钮被触发,您所设置的内容就会被调用。

关于java - 按下按钮时如何自动调用 EventHandler<ActionEvent>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58700934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com