【问题标题】:Same ActionEvent for multiple components多个组件的相同 ActionEvent
【发布时间】:2016-08-24 12:05:55
【问题描述】:

我有这样的代码,

component1.setOnAction((ActionEvent event) -> {
           for(int i=0; i<=10; i++){
            System.out.println(i);
           }
        });

component2.setOnAction((ActionEvent event) -> {
           for(int i=0; i<=10; i++){
            System.out.println(i);
           }
        });

为了避免重复代码,我正在尝试类似的东西,

component1.setOnAction(action);
component2.setOnAction(action);

在哪里,

action = // 我如何在这里定义 for 循环。

我试过了,

 ActionEvent action = new ActionEvent(Source, target); 

ActionEvent 构造函数要求提供源和目标(我不太清楚如何使用)。

我怎样才能做到这一点?

【问题讨论】:

  • 可以在setOnAction()中设置EventHandler,而不是ActionEvent。

标签: javafx actionevent


【解决方案1】:

setOnAction() 需要 EventHandler,而不是 ActionEvent。没有什么能阻止您定义 EventHandler 并将其重用于多个组件。

EventHandler predefinedHandler = (e) -> {
   for (int i = 0; i <= 10; i++) {
      System.out.println(i);
   }
};

component1.setOnAction(predefinedHandler);
component2.setOnAction(predefinedHandler);

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多