如何访问javafx动态按钮的事件处理程序

时间:2016-09-30 22:13:04

标签: java javafx

如何在gridpane中获取动态按钮的事件处理程序?

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在引用按钮对象时给出了错误。

1 个答案:

答案 0 :(得分: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();

}