Suppose we have 100 questions. Each question has a different number of answers. All these questions are listed in the database, which indicates how much each question has these answer choices. How do I dynamically change the contents of the container, for example, there were 3 answers in the question, the next question will be 4, how do I add this answer without changing the scene , somehow doing it from the controller or changing the fxml file?

  • What have you got so far? - 0xdb
  • Nothing happened ... I need to at least understand how to make it so that when I press the button, in the same scene, there is another completely different button. - Sergey Berezovsky

1 answer 1

An example of creating elements (without direct access to the "container")

import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) { Button button = new Button("Start button"); button.setOnAction(new CreateAnswerHandler()); Pane container = new VBox(button); primaryStage.setScene(new Scene(container, 300, 500)); primaryStage.show(); } } 

Process:

 import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Parent; import javafx.scene.control.Button; import javafx.scene.layout.Pane; public class CreateAnswerHandler implements EventHandler<ActionEvent> { public Button createAnswerButton() { Button button = new Button(String.valueOf(System.currentTimeMillis())); button.setOnAction(new CreateAnswerHandler()); return button; } @Override public void handle(ActionEvent event) { if ( event.getSource() instanceof Button ) { Button bSource = (Button) event.getSource(); Parent parent = bSource.getParent(); if ( parent != null && parent instanceof Pane ) { Pane pane = (Pane) parent; pane.getChildren().add(createAnswerButton()); } } } } 
  • May I ask you? And why do we do this kind of check: if (event.getSource () instanceof Button) {...} and if (parent! = Null && parent instanceof Pane) {...}. - Sergey Berezovsky
  • To avoid ClassCastException. Because a class is public, it is not only Button located on the Pane that can be used "potentially". - Alexander Savostyanov