2016-08-24 36 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); 
相關問題