简体   繁体   English

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

[英]How to access the event handler of javafx dynamic button

How do I get the event handler of my dynamic button in the 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");});
}

Because setOnAction gives me an error when refering to button object. 因为setOnAction在引用按钮对象时给我一个错误。

You have to just replace your code with this. 您只需要用此替换代码。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM