javafx make a grid of buttons

谁说胖子不能爱 提交于 2020-01-02 09:59:57

问题


I want to make a grid with a specific amount of buttons. I know how many buttons there are need to be because I get the number of rows and columns.

I could do a loop, but I don't know how you can place buttons next to eachother and underneath.
Secondly, the buttons need a Text and an Id, text is no problem, but how do you give them an id?
And at last, and probably most difficult, it can occur that there are a lot of rows, so that a scrollbar should be available.

At the end it should look something like this:


回答1:


@Override
public void start(Stage stage) {
    GridPane grid = new GridPane();
    grid.setPadding(new Insets(BUTTON_PADDING));
    grid.setHgap(BUTTON_PADDING);
    grid.setVgap(BUTTON_PADDING);

    for (int r = 0; r < NUM_BUTTON_LINES; r++) {
        for (int c = 0; c < BUTTONS_PER_LINE; c++) {
            int number = NUM_BUTTON_LINES * r + c;
            Button button = new Button(String.valueOf(number));
            grid.add(button, c, r);
        }
    }

    ScrollPane scrollPane = new ScrollPane(grid);

    stage.setScene(new Scene(scrollPane));
    stage.show();
}



回答2:


The best solution would be:

itemNumber starts from 0 to N: 
    Grid.getChildren().get(itemNumber).setId("bt"+itemNumber);
    Grid.getChildren().get(itemNumber).getId();


来源:https://stackoverflow.com/questions/29679971/javafx-make-a-grid-of-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!