fangio
fangio

Reputation: 1786

javafx make a grid of buttons

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:

enter image description here

Upvotes: 2

Views: 8431

Answers (2)

user8165084
user8165084

Reputation: 1

The best solution would be:

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

Upvotes: -1

fangio
fangio

Reputation: 1786

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

Upvotes: 5

Related Questions