2016-08-24 37 views
0

我有这样的代码,相同动作事件的多个组件

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); 

其中,

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

我试过,

ActionEvent action = new ActionEvent(Source, target); 

ActionEvent构造要求一个源和目标(这我不是关于如何使用很清楚)。

我该如何做到这一点?

+0

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

回答

3

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

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

component1.setOnAction(predefinedHandler); 
component2.setOnAction(predefinedHandler); 
相关问题