英文:
How to set an instance of the EventHandler interface as the action for a button
问题
我正在尝试通过将EventHandler<>
接口的实例传递给其setOnAction()
方法来设置按钮的操作,但是它不起作用。
Class 1:
public class Class1 {
private Class2 class2;
private Button buttonDelete = null;
private Button getButtonDelete() {
if (buttonDelete == null) {
buttonDelete = new Button("Delete");
buttonDelete.setOnAction(class2);
}
return buttonDelete;
}
}
Class 2:
public class Class2 implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
// do something
}
}
英文:
I am trying to set the action of a button by passing an instance of the EventHandler<>
interface to its setOnAction()
method, however it is not working.
Class 1:
public class Class1 {
private Class2 class2;
private Button buttonDelete = null;
private Button getButtonDelete() {
if (buttonDelete == null) {
buttonDelete = new Button("Delete");
buttonDelete.setOnAction(class2);
}
return buttonDelete;
}
}
Class 2:
public class Class2 implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
// do something
}
}
答案1
得分: 2
-
要调用构造函数:
new Class1(new Class2());
当事件触发时,将自动调用handle
方法。 -
长答案,使用匿名类更适合按钮事件处理,因此请了解匿名类和Lambda表达式,这是很好的学习。
英文:
- Short answer :
public Class1(Class2 class2){
this.class2 = class2;
}
To call the constructor : new Class1(new Class2());
the handle method will be called automatically when the event triggred.
- Long answer, using anonymous classes is better for button event handling so learn about anonymouse classes and lambda expressions, good learning.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论