2016-09-30 163 views
0

如何獲取我的動態按鈕在Gridpane中的事件處理程序?如何訪問javafx動態按鈕的事件處理程序

Stage window; 

public void start(Stage primaryStart) throws Exception{ 
    window = primaryStart; 
    window.setTitle("Minesweeper (Eventually)"); 
    //GridPane with 10px padding around edge 
    GridPane grid = new GridPane(); 
    grid.setPadding(new Insets(10, 10, 10, 10)); 
    for(int i = 0; i < 5; i++){ 
     for(int j = 0; j<5; j++){ 
      Button button = new Button("[]"); 
      GridPane.setConstraints(button, i,j); 
      grid.getChildren().add(button); 
     } 
    } 
    Scene scene = new Scene(grid, 300, 200); 
    window.setScene(scene); 
    window.show(); 
    button.setOnAction(e -> {System.out.println("Something");}); 
} 

因爲setOnAction在引用按鈕對象時給了我一個錯誤。

回答

0

你必須用這個替換你的代碼。

public void start(Stage primaryStart) throws Exception{ 
    window = primaryStart; 
    window.setTitle("Minesweeper (Eventually)"); 
    //GridPane with 10px padding around edge 
    GridPane grid = new GridPane(); 
    grid.setPadding(new Insets(10, 10, 10, 10)); 
    for(int i = 0; i < 5; i++){ 
     for(int j = 0; j<5; j++){ 
      Button button = new Button("[]"); 
      button.setOnAction(e -> {System.out.println("Something");}); 
      GridPane.setConstraints(button, i,j); 
      grid.getChildren().add(button); 
     } 
    } 
    Scene scene = new Scene(grid, 300, 200); 
    window.setScene(scene); 
    window.show(); 

} 
相關問題