简体   繁体   中英

Dynamically updating a GridPane with new Buttons in JavaFX -> how to repaint?

I have a grid pane which contains a number of buttons (normally something between 10 and 25) with five buttons per row (and however many are left in the last row). The number of buttons (and the buttons itself) might change during program execution. When that happens, the new buttons should be displayed. How can I achieve that? Here is a mini-example:

public class GridButtons extends Application {
    List<String> buttonTexts = new ArrayList<>();
    GridPane buttonGrid = new GridPane();
    GridPane bgGrid = new GridPane();

    @Override
    public void start(Stage primaryStage) {
        Button changeButtonsButton = new Button("Change BTNs");
        changeButtonsButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                changeButtonTexts();
            }
        });
        bgGrid.add(changeButtonsButton, 0, 0);
        changeButtonTexts();
        bgGrid.add(buttonGrid, 1, 0);

        Scene scene = new Scene(bgGrid, 440, 140);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public void updateButtonsGrid() {
        buttonGrid = new GridPane();
        for (int i = 0; i < buttonTexts.size(); i++) {
            Button button = new Button(buttonTexts.get(i));
            button.setMinWidth(70);
            button.setMaxWidth(70);
            buttonGrid.add(button, i % 5, i / 5);
            System.out.println(buttonTexts.get(i));
        }
        // now the new GridPane should be displayed -> how?
    }

    public void changeButtonTexts() {
        buttonTexts.clear();
        Random random = new Random();
        int buttonCount = random.nextInt(15) + 10;
        for (int i = 0; i < buttonCount; i++) {
            buttonTexts.add("Button " + i);
        }
        updateButtonsGrid();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Or are there better options than using a GridPane ? Using a ListView<Button> and an ObservableList<Button> would work, but then the buttons are not displayed in a tabular form with five buttons in each row.

Creating a new GridPane is probably not what you want here. In the function updateButtonsGrid , change the line

buttonGrid = new GridPane();

to

buttonGrid.getChildren().clear();

If, for some reason, you are absolutely sure you need a new instance of GridPane , remove the old one from bgGrid , and add the new one. In your current code example the new instance of GridPane is never added to the scene graph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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