Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX : Adding a new node to Scene in java code when Scene is initially loaded from FXML

Tags:

fxml

javafx-2

How can I add a new node to the Scene in java code when Scene is initially loaded from FXML ? I have loaded from FXML as shown below

Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

Scene scene = new Scene(root, 1000, 600, Color.DODGERBLUE);

Now say for example how do I add button to the scene in Java code?

like image 427
thiru_k Avatar asked Aug 09 '13 17:08

thiru_k


People also ask

Can a node be placed in a scene JavaFX?

Each JavaFX Node (subclass) instance can only be added to the JavaFX scene graph once. In other words, each Node instance can only appear in one place in the scene graph. If you try to add the same Node instance, or Node subclass instance, to the scene graph more than once, JavaFX will throw an exception!

Which method is used to add scene to stage?

You can add a Scene object to the stage using the method setScene() of the class named Stage.


2 Answers

I do not know the reason behind your question. If what you want is to insert some nodes dynamically during the application or scene initialization, I suggest you use a initialize method at your controller.

This method must be annotated with @FXML and have the following signature:

void initialize()

Then, you can inject the container where the button must be inserted on the controller and add the button to it:

@FXML
HBox buttonBox // assuming your button container is a HBox
...

@FXML
protected void initialize() {
    buttonBox.getChildren().add(new Button("Click me!"));
}

The method initialize is called after the components defined at the FXML file were built.

like image 54
Crferreira Avatar answered Jan 04 '23 11:01

Crferreira


Here is one way to do this:

((VBox) root).getChildren().add(new Button("Java Button"));

The snippet above assumes that the top container defined in your FXML is a VBox, if it is not a VBox, just cast it to whatever type you have chosen.

I wonder how I can determine the type of the container at runtime, so I can write a more generic code.

The type is likely a Pane, so casting to a Pane will work in most cases. Using a layout Pane as a Parent is usually recommended for most layout tasks in JavaFX.

like image 30
jewelsea Avatar answered Jan 04 '23 09:01

jewelsea