Using the ToolBar Class in JavaFX - dummies

Using the ToolBar Class in JavaFX

By Doug Lowe

JavaFX includes a ToolBar class that lets you create horizontal or vertical toolbars. These toolbars can contain buttons and several other types of JavaFX controls.

The following table lists the constructors and methods of the ToolBar class.

Constructor Description
ToolBar() Creates an empty toolbar.
ToolBar(Node nodes…) Creates a toolbar with the specified nodes.
Method Description
ObservableList getItems() Gets the items in the toolbar.
void setOrientation(Orientation
value)
Sets the orientation of the toolbar. Allowable values are Orientation.HORIZONTAL or Orientation.VERTICAL. The default orientation
is horizontal.

The following figure shows the scene displayed by a sample program that creates both a horizontal and a vertical toolbar containing buttons, check boxes, and radio buttons. Separators are used to create visual separation between the groups of controls in the toolbar.

A program with two toolbars.
A program with two toolbars.

The following code is the program that created the toolbars shown in Figure 1.

import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;
public class ToolBarGame extends Application
{
    public static void main(String[] args)
    {
        launch(args);
    }
    @Override public void start(Stage primaryStage)
    {
        Button btnNew = new Button("New");
        Button btnPause = new Button("Pause");
        Button btnQuit = new Button("Quit");
        CheckBox chkSound = new CheckBox("Sound");
        CheckBox chkMusic = new CheckBox("Music");
        RadioButton rdoEasy = new RadioButton("Easy");
        RadioButton rdoMedium = new RadioButton("Medium");
        RadioButton rdoHard = new RadioButton("Hard");
        ToggleGroup groupDifficulty = new ToggleGroup();
        groupDifficulty.getToggles().addAll(
                rdoEasy,
                rdoMedium,
                rdoHard
            );
        ToolBar toolBar1 = new ToolBar();
        toolBar1.getItems().addAll(
                new Separator(),
                btnNew,
                btnPause,
                btnQuit,
                new Separator(),
                chkSound,
                chkMusic,
                new Separator()
            );
        ToolBar toolBar2 = new ToolBar();
        toolBar2.setOrientation(Orientation.VERTICAL);
        toolBar2.getItems().addAll(
                new Separator(),
                rdoEasy,
                rdoMedium,
                rdoHard,
                new Separator()
            );
        BorderPane pane = new BorderPane();
        pane.setTop(toolBar1);
        pane.setLeft(toolBar2);
        Scene scene = new Scene(pane, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ToolBar Sample");
        primaryStage.show();
    }
}