javafx 制作一个按钮网格

2022-01-18 00:00:00 button grid java javafx

我想用特定数量的按钮制作一个网格.我知道需要多少按钮,因为我得到了行数和列数.

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.

我可以做一个循环,但我不知道如何将按钮放在彼此旁边和下方.
其次,按钮需要一个Text和一个Id,text没问题,但是怎么给它们一个id呢?
最后,也可能是最困难的,可能会出现很多行,因此滚动条应该可用.

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.

最后应该是这样的:

推荐答案

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

相关文章