Tech and Media Labs
This site uses cookies to improve the user experience.




JavaFX Group

Jakob Jenkov
Last update: 2016-05-21

The JavaFX Group component is a container component which applies no special layout to its children. All child components (nodes) are positioned at 0,0 . A JavaFX Group component is typically used to apply some effect or transformation to a set of controls as a whole - as a group. If you need some layout to the children inside the Group, nest them inside layout components and add the layout components to the Group. The JavaFX Group component is represented by the class javafx.scene.Group .

Creating a Group

You create a JavaFX Group instance via its constructor. Here is a JavaFX Group instantiation example:

Group group = new Group();

Adding Components to a Group

You can add components to a JavaFX Group by obtaining its list of children and adding the children to that list. Here is an example of adding children to a JavaFX Group:

Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button 2");

Group group = new Group();

group.getChildren().add(button1);
group.getChildren().add(button2);

Adding a Group to the Scene Graph

To make a JavaFX Group instance visible it must be added to the JavaFX scene graph. That means adding the Group instance to a Scene object or adding the Group instance to a layout component which is then added to a Scene object.

Here is an example of adding a JavaFX Group instance to the JavaFX scene graph:

package com.jenkov.javafx.layouts;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;


public class GroupExperiments extends Application  {


    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("HBox Experiment 1");

        Button button1 = new Button("Button Number 1");
        Button button2 = new Button("Button 2");

        Group group = new Group();

        group.getChildren().add(button1);
        group.getChildren().add(button2);

        Scene scene = new Scene(group, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

The application resulting from running the above code would look similar to this:

A JavaFX Group component with two buttons added to the scene graph

As you can see, the two buttons are positioned on top of each other, because both buttons are positioned at 0,0 inside the Group component.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC