如何将EventHandler接口的一个实例设置为按钮的动作

huangapple go评论76阅读模式
英文:

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&lt;&gt; 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(&quot;Delete&quot;);
           buttonDelete.setOnAction(class2);
       }
       return buttonDelete;
   }
}

Class 2:

public class Class2 implements EventHandler&lt;ActionEvent&gt; {
    @Override
	public void handle(ActionEvent event) {
        // do something
    }
}

答案1

得分: 2

  1. 要调用构造函数:new Class1(new Class2()); 当事件触发时,将自动调用handle方法。

  2. 长答案,使用匿名类更适合按钮事件处理,因此请了解匿名类和Lambda表达式,这是很好的学习。

英文:
  1. 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.

  1. Long answer, using anonymous classes is better for button event handling so learn about anonymouse classes and lambda expressions, good learning.

huangapple
  • 本文由 发表于 2020年7月21日 21:08:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63015235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定