JavaFX

JavaFX Tutorial for Beginners

Photo of Andreas PomarolliAndreas PomarolliFebruary 15th, 2016Last Updated: April 24th, 2019
1 3,093 30 minutes read

JavaFX is an open source Java-based framework for developing rich client applications. It is comparable to other frameworks on the market such as Adobe Flex and Microsoft Silverlight.

JavaFX is also seen as the successor of Swing in the arena of graphical user interface (GUI) development technology in Java platform. The JavaFX library is available as a public Java application programming interface (API).
 
 
 
 
 
 

 
The following table shows an overview of the whole tutorial:

The following examples uses Java SE 7 and JavaFX 2.2.

1. Introduction

The GUI in JavaFX is constructed as a scene graph. A scene graph is a collection of visual elements, called nodes, arranged in a hierarchical fashion. A scene graph is built using the public JavaFX API. Nodes in a scene graph can handle user inputs and user gestures. They can have effects, transformations, and states.

Types of nodes in a scene graph include simple UI controls such as buttons, text fields, two-dimensional (2D) and three-dimensional (3D) shapes, images, media (audio and video), web content, and charts.

2. Your First JavaFX Application

2.1 The Code

FxFirstExample.java

import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.layout.VBox;import javafx.scene.text.Text;import javafx.stage.Stage;public class FxFirstExample extends Application{public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the TextText text = new Text("Hello JavaFX");// Create the VBoxVBox root = new VBox();// Add the Text to the VBoxroot.getChildren().add(text);// Set the Size of the VBoxroot.setMinSize(350, 250);// Create the SceneScene scene = new Scene(root);// Set the Properties of the Stagestage.setX(100);stage.setY(200);stage.setMinHeight(300);stage.setMinWidth(400);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("Your first JavaFX Example");// Display the Stagestage.show();}}

2.2 Overriding the start() Method

A JavaFX application is a class that must inherit from theApplication class that is in thejavafx.application package. So it is necessary to override thestart() method.

@Overridepublic void start(Stage stage){// do something}

Thestart() method is the entry point for a JavaFX application. It is called by the JavaFX application launcher. Notice that thestart() method is passed an instance of theStage class, which is known as the primary stage of the application. You can create more stages as necessary in your application. However, the primary stage is always created by the JavaFX runtime.

2.3 Showing the Stage

Similar to a stage in the real world, a JavaFXstage is used to display aScene. Ascene has visuals, such as text, shapes, images, controls, animations, and effects, with which the user may interact, as is the case with all GUI-based applications.

Astage in JavaFX is a top-level container that hosts ascene, which consists of visual elements. TheStage class represents a stage in a JavaFX application. The primarystage is created by the platform and passed to thestart(Stage s) method of theApplication class.

@Overridepublic void start(Stage stage){// Display the Stagestage.show();}

The bounds of astage consist of four properties:

  • X
  • Y
  • Width
  • Height

Thex andy properties determine the location of the upper-left corner of thestage. Thewidth andheight properties determine its size.

// Set the Properties of the Stagestage.setX(100);stage.setY(200);stage.setMinHeight(300);stage.setMinWidth(400);

The primary stage created by the application launcher does not have ascene. You have to create ascene for yourstage. You must show thestage to see the visuals contained in itsscene. Use theshow() method to show thestage. Optionally, you can set a title for the stage using thesetTitle() method.

// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("Your first JavaFX Example");// Display the Stagestage.show();

2.4 Launching the Application

You can use one of the following two options to run a JavaFX Application:

It is not necessary to have amain() method in the class to start a JavaFX application. When you run a Java class that inherits from theApplication class, the java command launches the JavaFX application if the class being run does not contain themain() method.

If you include amain() method in the JavaFX application class inside themain() method, call thelaunch() static method of theApplication class to launch the application. Thelaunch() method takes aString array as an argument, which are the parameters passed to the JavaFX application.

If you are using the first option, you do not need to write amain() method for theFxFirstExample class. If you are using the second option, theHelloFXApp class has to be enriched with themain() method.

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

2.5 Adding a Scene to the Stage

An instance of theScene class represents a scene. Astage contains onescene, and ascene contains visual contents. The contents of thescene are arranged in a tree-like hierarchy. At the top of the hierarchy is the root node. The root node may contain child nodes, which in turn may contain their child nodes, and so on. You must have a root node to create ascene. You can use aVBox or another node type as the root node.VBox stands for Vertical box, which arranges its children vertically in a column.

The following code snippet adds thescene to thestage:

// Add the scene to the Stagestage.setScene(scene);

2.6 The GUI

Yout First JavaFX Example
Yout First JavaFX Example

3. Controls

3.1 Introduction

JavaFX lets you create applications using GUI components. An application with a GUI performs three tasks:

  • Accepts inputs from the user through input devices such as a keyboard or a mouse
  • Processes the inputs
  • Displays outputs

The UI provides a means to exchange information in terms of input and output between an application and its users. Entering text using a keyboard, selecting a menu item using a mouse, clicking a button, or other actions are examples of providing input to a GUI application. The application displays outputs on a computer monitor using text, charts, dialog boxes, and so forth.

Users interact with a GUI application using graphical elements called controls or widgets. Buttons, labels, text fields, text area, radio buttons, and check boxes are a few examples of controls. Devices like a keyboard, a mouse, and a touch screen are used to provide input to controls. Controls can also display output to the users. Controls generate events that indicate an occurrence of some kind of interaction between the user and the control. For example, pressing a button using a mouse or a spacebar generates an action event indicating that the user has pressed the button.

3.2 Label

An instance of theLabel class represents a label control. As the name suggest, aLabel is simply a label that is used to identify or describe another component on a screen. It can display a text, an icon, or both. Typically, aLabel is placed next to (to the right or left) or at the top of the node it describes. ALabel is not focus traversable. That is, you cannot set the focus to aLabel using the Tab key. ALabel control does not generate any interesting events that are typically used in an application.

3.2.1 The Code

FxLabelExample.java

import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.TextField;import javafx.scene.layout.GridPane;import javafx.stage.Stage;public class FxLabelExample extends Application{public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the Text FieldsTextField firstNameFld = new TextField();TextField lastNameFld = new TextField();// Create the LabelsLabel firstNameLbl = new Label("_First Name:");Label lastNameLbl = new Label("_Last Name:");// Bind the Label to the according FieldfirstNameLbl.setLabelFor(firstNameFld);// Set mnemonic parsing to the LabelfirstNameLbl.setMnemonicParsing(true);// Bind the Label to the according FieldlastNameLbl.setLabelFor(lastNameFld);// Set mnemonic parsing to the LabellastNameLbl.setMnemonicParsing(true);// Create the GridPaneGridPane root = new GridPane();// Add the Labels and Fields to the GridPaneroot.addRow(0, firstNameLbl, firstNameFld);root.addRow(1, lastNameLbl, lastNameFld);// Set the Size of the GridPaneroot.setMinSize(350, 250);/*  * Set the padding of the GridPane * Set the border-style of the GridPane * Set the border-width of the GridPane * Set the border-insets of the GridPane * Set the border-radius of the GridPane * Set the border-color of the GridPane*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Label Example");// Display the Stagestage.show();}}

The above example shows a window with twoLabel controls with text First Name: and Last Name: TheLabel with the text First Name: is an indicator for the user that he should enter a first name in the field that is placed right next to it. A similar argument goes for the Last Name:Label control.

3.2.2 Adding a Mnemonic to a Label

ALabel control can have a mnemonic.Mnemonic parsing forLabel controls is set to false by default. When you press the mnemonic key for a Label, the focus is set to thelabelFor node for thatLabel. The following snippet of code creates aTextField and aLabel. TheLabel sets a mnemonic, enables mnemonic parsing, and sets theTextField as itslabelFor property.

// Create the Text FieldsTextField firstNameFld = new TextField();TextField lastNameFld = new TextField();// Create the LabelsLabel firstNameLbl = new Label("_First Name:");Label lastNameLbl = new Label("_Last Name:");// Bind the Label to the according FieldfirstNameLbl.setLabelFor(firstNameFld);// Set mnemonic parsing to the LabelfirstNameLbl.setMnemonicParsing(true);// Bind the Label to the according FieldlastNameLbl.setLabelFor(lastNameFld);// Set mnemonic parsing to the LabellastNameLbl.setMnemonicParsing(true);

The topicTextField will be discussed in the next section.

AGridPane contains all labels and text fields in the above example. A full description of the classGridPane,VBox and other panes, which are used in all examples is available in the articleJavaFX Layout Example.

3.2.3 The GUI

A JavaFX Label Example
A JavaFX Label Example

3.3 TextField

ATextField is a text input control. It inherits from the ATextInputControl class. It lets the user enter a single line of plain text. If you need a control to enter multiline text, useTextArea instead. Newline and tab characters in the text are removed.

3.3.1 The Code

FxTextFieldExample.java

import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.TextField;import javafx.scene.layout.GridPane;import javafx.stage.Stage;public class FxTextFieldExample extends Application{// Create the Message LabelLabel messageLbl = new Label("Enter your Name into the Text Fields.");public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the TextFieldsTextField firstNameFld = new TextField();TextField lastNameFld = new TextField();// Both fields should be wide enough to display 15 charsfirstNameFld.setPrefColumnCount(15);lastNameFld.setPrefColumnCount(15);// Set ActionEvent handlers for both fieldsfirstNameFld.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have changed the First Name!");            }        });lastNameFld.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have changed the Last Name !");            }        });GridPane root = new GridPane();// Set the horizontal spacing to 10pxroot.setHgap(10);// Set the vertical spacing to 5pxroot.setVgap(5);// Add Labels and Fields to the GridPaneroot.addRow(0, messageLbl);root.addRow(1, new Label("First Name:"), firstNameFld);root.addRow(2, new Label("Last Name:"), lastNameFld);// Set the Size of the GridPaneroot.setMinSize(350, 250);/*  * Set the padding of the GridPane * Set the border-style of the GridPane * Set the border-width of the GridPane * Set the border-insets of the GridPane * Set the border-radius of the GridPane * Set the border-color of the GridPane*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A TextField Example");// Display the Stagestage.show();}// Helper Methodpublic void printMessage(String message){// Set the Text of the LabelmessageLbl.setText(message);}}

3.3.2 Setting the width of a TextField

TheprefColumnCount property determines the width of the control. TheTextField in ur example is wide enough
to display fiteen letters

// Both fields should be wide enough to display 15 charsfirstNameFld.setPrefColumnCount(15);lastNameFld.setPrefColumnCount(15);

3.3.3 Adding ActionEvent Handler to a TextField

TheonAction property is anActionEvent handler, which is called when the Enter key is pressed in theTextField, as shown in the following code:

// Set ActionEvent handlers for both fieldsfirstNameFld.setOnAction(new EventHandler<ActionEvent>() {@Override public void handle(ActionEvent e) {printMessage("You have changed the First Name!");}});lastNameFld.setOnAction(new EventHandler<ActionEvent>() {@Override public void handle(ActionEvent e) {printMessage("You have changed the Last Name !");}});

3.3.4 The GUI

After starting the application, the following window appears:

A JavaFX TextField Example
A TextField Example before inserting data

After inserting text into theTextField, the message will be changed:

A JavaFX TextField Example
A TextField Example after inserting data

3.4 Button

A button that executes a command when activated is known as a command button. TheButton,Hyperlink, andMenuButton classes represent command buttons. AMenuButton lets the user execute a command from a list of commands. Buttons used for presenting different choices to users are known as choice buttons. TheToggleButton,CheckBox, andRadioButton classes represent choice buttons. The third kind of button is a hybrid of the first two kinds. They let users execute a command or make choices.

3.4.1 The Code

FxButtonExample.java

import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxButtonExample extends Application{// Create the Message LabelLabel messageLbl = new Label("Press any Button to see the message");public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create a normal button with N as its mnemonicButton newBtn = new Button("_New");// Add EventHandler to the ButtonnewBtn.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have pressed the new Button");            }        });// Create a default button with S as its mnemonicButton saveBtn = new Button("_Save");// Set this Button as the DefaultsaveBtn.setDefaultButton(true);// Add EventHandler to the ButtonsaveBtn.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have pressed the save Button");            }        });// Create a cancel button with C as its mnemonicButton cancelBtn = new Button("_Cancel");cancelBtn.setCancelButton(true);// Add EventHandler to the ButtoncancelBtn.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have pressed the cancel Button");            }        });// Create the HBoxHBox buttonBox = new HBox();// Add the children to the HBoxbuttonBox.getChildren().addAll(newBtn, saveBtn, cancelBtn);// Set the vertical spacing between children to 15pxbuttonBox.setSpacing(15);// Create the VBoxVBox root = new VBox();// Add the children to the VBoxroot.getChildren().addAll(messageLbl, buttonBox);// Set the vertical spacing between children to 15pxroot.setSpacing(15);// Set the Size of the VBoxroot.setMinSize(350, 250);/*  * Set the padding of the VBox * Set the border-style of the VBox * Set the border-width of the VBox * Set the border-insets of the VBox * Set the border-radius of the VBox * Set the border-color of the VBox*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Button Example");// Display the Stagestage.show();}// Helper Methodpublic void printMessage(String message){// Set the Text of the LabelmessageLbl.setText(message);}}

3.4.2 Adding ActionEvent Handler to a Button

An instance of theButton class represents a command button. Typically, aButton has text as its label and anActionEvent handler is registered to it. ThemnemonicParsing property for theButton class is set to true by default.

// Create a normal button with N as its mnemonicButton newBtn = new Button("_New");// Add EventHandler to the ButtonnewBtn.setOnAction(new EventHandler<ActionEvent>() {@Override public void handle(ActionEvent e) {printMessage("You have pressed the new Button");}});

3.4.3 Setting the mode of a Button

AButton can be in one of three modes:

  • A normal button
  • A default button
  • A cancel button

For a normal button, itsActionEvent is fired when the button is activated. For a default button, theActionEvent is fired when the Enter key is pressed and no other node in the scene consumes the key press.

// Create a default button with S as its mnemonicButton saveBtn = new Button("_Save");// Set this Button as the DefaultsaveBtn.setDefaultButton(true);// Add EventHandler to the ButtonsaveBtn.setOnAction(new EventHandler<ActionEvent>() {@Override public void handle(ActionEvent e) {printMessage("You have pressed the save Button");}});

For a cancel button, theActionEvent is fired when the Esc key is pressed and no other node in the scene consumes the key press. By default, aButton is a normal button. The default and cancel modes are represented by thedefaultButton andcancelButton properties. You would set one of these properties to true to make a button a default or cancel button. By default, both properties are set to false.

// Create a cancel button with C as its mnemonicButton cancelBtn = new Button("_Cancel");cancelBtn.setCancelButton(true);// Add EventHandler to the ButtoncancelBtn.setOnAction(new EventHandler<ActionEvent>() {@Override public void handle(ActionEvent e) {printMessage("You have pressed the cancel Button");}});

The following snippet of code creates a normal button and adds anActionEvent handler. When the button is activated, for example, by clicking using a mouse, theprintMessage() method is called:

// Create a normal button with N as its mnemonicButton newBtn = new Button("_New");// Add EventHandler to the ButtonnewBtn.setOnAction(new EventHandler<ActionEvent>() {@Override public void handle(ActionEvent e) {printMessage("You have pressed the new Button");}});

3.4.4 The GUI

After starting the application, the following window appears:

A JavaFX Button Example
A ButtonExample before pressing any Button

After pressing anyButton, the message will be changed:

A JavaFX Button Example
A ButtonExample after pressing any Button

3.5 MenuButton

AMenuButton control looks like a button and behaves like a menu. When it is activated, it shows a list of options in the form of a pop-up menu. The list of options in the menu is maintained in anObservableList<MenuItem> whose reference is returned by thegetItems() method. To execute a command when a menu option is selected, you need to add theActionEvent handler to theMenuItem.

3.5.1 The Code

FxMenuButtonExample.java

import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.MenuButton;import javafx.scene.control.MenuItem;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxMenuButtonExample extends Application{// Create the Message LabelLabel messageLbl = new Label("Choose your car!");public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the MenuItem fordMenuItem ford = new MenuItem("Ford");// Add EventHandler to the MenuItemford.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have selected: Ford");            }        });// Create the MenuItem audiMenuItem audi = new MenuItem("Audi");// Add EventHandler to the MenuItemaudi.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have selected: Audi");            }        });// Create the MenuItem ferrariMenuItem ferrari = new MenuItem("Ferrari");// Add EventHandler to the MenuItemferrari.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have selected: Ferrari");            }        });// Create the MenuItem porscheMenuItem porsche = new MenuItem("Porsche");// Add EventHandler to the MenuItemporsche.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have selected: Porsche");            }        });// Create the MenuButtonMenuButton cars = new MenuButton("Select");// Add menu items to the MenuButtoncars.getItems().addAll(ford, audi, ferrari, porsche);// Create the VBoxVBox root = new VBox();// Add the children to the VBoxroot.getChildren().addAll(cars, messageLbl);// Set the Size of the VBoxroot.setMinSize(350, 250);/*  * Set the padding of the VBox * Set the border-style of the VBox * Set the border-width of the VBox * Set the border-insets of the VBox * Set the border-radius of the VBox * Set the border-color of the VBox*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A MenuButton Example");// Display the Stagestage.show();}// Helper Methodpublic void printMessage(String message){// Set the Text of the LabelmessageLbl.setText(message);}}

3.5.2 The GUI

After starting the application, the following window appears:

A JavaFX MenuButton Example
A MenuButton Example after pressing any Button

After pressing anyMenuButton, the message will be changed:

A JavaFX MenuButton Example
A MenuButton Example before pressing any Button

3.6 CheckBox

ACheckBox is a three-state selection control:

  • Checked
  • Unchecked
  • Undefined

Theundefined state is also known as anindeterminate state. ACheckBox supports a selection of three choices:

  • True
  • False
  • Unknown

or

  • Yes
  • No
  • Unknown

Usually, aCheckBox has text as a label. Clicking aCheckBox transitions it from one state to another cycling through three states. A box is drawn for aCheckBox. In theunchecked state, the box is empty. A tick mark is present in the box when it is in thechecked state. In theundefined state, a horizontal line is present in the box.

3.6.1 The Code

FxCheckBoxExample.java

import javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.scene.Scene;import javafx.scene.control.CheckBox;import javafx.scene.control.Label;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxCheckBoxExample extends Application{// Create the Selection LabelLabel selectionMsg = new Label("Choose your Car");public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create a CheckBox to support only two statesCheckBox fordCbx = new CheckBox("Ford");// Create a CheckBox to support three statesCheckBox audiCbx = new CheckBox("Audi");audiCbx.setAllowIndeterminate(true);// Add a ChangeListener to the CheckBox fordCbxfordCbx.selectedProperty().addListener(new ChangeListener<Boolean>(){    public void changed(ObservableValue<? extends Boolean> ov,    final Boolean value, final Boolean newValue) {    if(newValue != null && newValue)    {    printMessage("Your Selection: Ford");    }}});// Add a ChangeListener to the CheckBox audiCbxaudiCbx.selectedProperty().addListener(new ChangeListener<Boolean>(){    public void changed(ObservableValue<? extends Boolean> ov,    final Boolean value, final Boolean newValue) {    if(newValue != null && newValue)    {    printMessage("Your Selection: Audi");    }}});// Add a ChangeListener to the CheckBox audiCbxaudiCbx.indeterminateProperty().addListener(new ChangeListener<Boolean>(){    public void changed(ObservableValue<? extends Boolean> ov,    final Boolean value, final Boolean newValue) {    if(newValue != null && newValue)    {    printMessage("Your indeterminate Selection: Audi");    }}});// Create the VBoxVBox root = new VBox();// Add the children to the VBoxroot.getChildren().addAll(selectionMsg, fordCbx, audiCbx);// Set the vertical spacing between children to 20pxroot.setSpacing(20);// Set the Size of the VBoxroot.setMinSize(350, 250);/*  * Set the padding of the VBox * Set the border-style of the VBox * Set the border-width of the VBox * Set the border-insets of the VBox * Set the border-radius of the VBox * Set the border-color of the VBox*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A CheckBox Example");// Display the Stagestage.show();}// Helper Methodpublic void printMessage(String message){// Set the Text of the LabelselectionMsg.setText(message);}}

By default, theCheckBox control supports only the two stateschecked andunchecked. TheallowIndeterminate property specifies whether the third state (the undefined state) is available for selection. By default, it is set to false.

// Create a CheckBox to support three statesCheckBox audiCbx = new CheckBox("Audi");audiCbx.setAllowIndeterminate(true);

3.6.2 The ObservableValue Class

TheObservableValue interface inherits from theObservable interface. AnObservableValue wraps a value, which can be observed for changes. It has agetValue() method that returns the value it wraps. It generates invalidation events and change events. Invalidation events are generated when the value in theObservableValue is no longer valid. Change events are generated when the value changes. You can register a ChangeListener to anObservableValue. Thechanged() method of theChangeListener is called every time the value of its value changes. Thechanged() method receives three arguments:

  • The reference of the ObservableValue
  • The old value
  • The new value

The following code snippet shows an example of the usage of anObservableValue:

// Add a ChangeListener to the CheckBox audiCbxaudiCbx.indeterminateProperty().addListener(new ChangeListener<Boolean>(){public void changed(ObservableValue<? extends Boolean> ov,final Boolean value, final Boolean newValue) {if(newValue != null && newValue){printMessage("Your indeterminate Selection: Audi");}}});

3.6.3 The GUI

After starting the application, the following window appears:

A JavaFX CheckBox Example
A CheckBox Example before Selection

If you make a click on a specificCheckBox, the following message apperas in our example:

A JavaFX CheckBox Example
A CheckBox Example after Selection

3.7 ToggleButton

ToggleButton is a two-state button control. The two states are:

  • Selected
  • Unselected

Itsselected property indicates whether it is selected. Theselected property is true when it is in the selected state. Otherwise, it is false. When it is in the selected state, it stays depressed. You can toggle between the selected and unselected states by pressing it, and hence it got the nameToggleButton. ForToggleButtons, mnemonic parsing is enabled by default.

3.7.1 The Code

FxToggleButtonExample.java

import javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.Toggle;import javafx.scene.control.ToggleButton;import javafx.scene.control.ToggleGroup;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxToggleButtonExample extends Application{// Create the Message LabelLabel selectionMsg = new Label("Your selection: None");public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create four ToggleButtonsToggleButton fordBtn = new ToggleButton("Ford");ToggleButton audiBtn = new ToggleButton("Audi");ToggleButton ferrariBtn = new ToggleButton("Ferrari");ToggleButton porscheBtn = new ToggleButton("Porsche");// Create a ToggleGroupfinal ToggleGroup group = new ToggleGroup();// Add all ToggleButtons to a ToggleGroupgroup.getToggles().addAll(fordBtn, audiBtn, ferrariBtn, porscheBtn);// Create a ChangeListener for the ToggleGroupgroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){    public void changed(ObservableValue<? extends Toggle> ov,            final Toggle toggle, final Toggle new_toggle)     {    String toggleBtn = ((ToggleButton)new_toggle).getText();    selectionMsg.setText("Your selection: " + toggleBtn);            }});// Create the Label for the SelectionLabel selectLbl = new Label("Select the car you like:");// Create a HBoxHBox buttonBox = new HBox();// Add ToggleButtons to an HBoxbuttonBox.getChildren().addAll(fordBtn, audiBtn, ferrariBtn, porscheBtn);// Set the spacing between children to 10pxbuttonBox.setSpacing(10);// Create the VBoxVBox root = new VBox();// Add the Labels and HBox to the VBoxroot.getChildren().addAll(selectionMsg, selectLbl, buttonBox);// Set the spacing between children to 10pxroot.setSpacing(10);// Set the Size of the VBoxroot.setMinSize(350, 250);/*  * Set the padding of the VBox * Set the border-style of the VBox * Set the border-width of the VBox * Set the border-insets of the VBox * Set the border-radius of the VBox * Set the border-color of the VBox*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A ToggleButton Example");// Display the Stagestage.show();}}

3.7.2 The GUI

After starting the application, the following window appears:

A JavaFX ToggleButton Example
A ToggleButton Example before pressing any Button

After pressing anyToggleButton, the message will be changed:

A JavaFX ToggleButton Example
A ToggleButton Example after pressing any Button
Want to master JavaFX ?
Subscribe to our newsletter and download theJavaFXProgramming Cookbookright now!
In order to get you prepared for your JavaFX development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

3.8 RadioButton

An instance of theRadioButton class represents a radio button. It inherits from theToggleButton class. Therefore, it has all of the features of a toggle button. A radio button is rendered differently compared to a toggle button. Like a toggle button, a radio button can be in one of the two states:

  • Selected
  • Unselected

Itsselected property indicates its current state. Like a toggle button, its mnemonic parsing is enabled by default. Like a toggle button, it also sends anActionEvent when it is selected and unselected.

3.8.1 The Code

FxRadioButtonExample.java

import javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.RadioButton;import javafx.scene.control.Toggle;import javafx.scene.control.ToggleButton;import javafx.scene.control.ToggleGroup;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxRadioButtonExample extends Application{// Create the Selection LabelLabel selectionMsg = new Label("Your selection: None");public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the RadioButtonsRadioButton fordBtn = new RadioButton("Ford");RadioButton audiBtn = new RadioButton("Audi");RadioButton ferrariBtn = new RadioButton("Ferrari");RadioButton porscheBtn = new RadioButton("Porsche");// Create a ToggleGroupToggleGroup group = new ToggleGroup();// Add all RadioButtons to a ToggleGroupgroup.getToggles().addAll(fordBtn, audiBtn, ferrariBtn, porscheBtn);// Add a listener to the ToggleGroupgroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){    public void changed(ObservableValue<? extends Toggle> ov,            final Toggle toggle, final Toggle new_toggle)     {    String toggleBtn = ((ToggleButton)new_toggle).getText();    selectionMsg.setText("Your selection: " + toggleBtn);            }});// Select the default car as ferrariferrariBtn.setSelected(true);// Create the Selection LabelLabel msg = new Label("Select the car you like the most:");// Create a HBoxHBox buttonBox = new HBox();// Add RadioButtons to an HBoxbuttonBox.getChildren().addAll(fordBtn, audiBtn, ferrariBtn, porscheBtn);// Set the spacing between children to 10pxbuttonBox.setSpacing(10);// Create the VBoxVBox root = new VBox();// Add Labels and RadioButtons to an VBoxroot.getChildren().addAll(selectionMsg, msg, buttonBox);// Set the spacing between children to 10pxroot.setSpacing(10);// Set the Size of the VBoxroot.setMinSize(350, 250);/*  * Set the padding of the VBox * Set the border-style of the VBox * Set the border-width of the VBox * Set the border-insets of the VBox * Set the border-radius of the VBox * Set the border-color of the VBox*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A RadioButton Example");// Display the Stagestage.show();}}

There is a significant difference in the use of radio buttons compared to the use of toggle buttons. Recall that when toggle buttons are used in a group, there may not be any selected toggle button in the group. When radio buttons are used in a group, there must be one selected radio button in the group. Unlike a toggle button, clicking a selected radio button in a group does not unselect it. To enforce the rule that one radio button must be selected in a group of radio buttons, one radio button from the group is selected programmatically by default.

3.8.2 The GUI

After starting the application, the following window appears:

A JavaFX RadioButton Example
A RadioButton Example before pressing any Button

After pressing anyRadioButton, the message will be changed:

A JavaFX RadioButton Example
A RadioButton Example after pressing any Button

3.9 ChoiceBox

AChoiceBox is used to let a user select an item from a small list of items. The items may be any type of objects. AChoiceBox is a parameterized class. The parameter type is the type of the items in its list. If you want to store mixed types of items in aChoiceBox, you can use its raw type, as shown in the following code:

3.9.1 The Code

FxChoiceBoxExample.java

import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.ChoiceBox;import javafx.scene.control.Label;import javafx.scene.layout.GridPane;import javafx.stage.Stage;public class FxChoiceBoxExample extends Application{public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the Label for the CarLabel carLbl = new Label("Car:");// Create a ChoiceBox for carsChoiceBox<String> cars = new ChoiceBox<>();// Add the items to the ChoiceBoxcars.getItems().addAll("Ford", "Audi", "Ferrari", "Porsche");// Create the Selection Message LabelLabel selectionMsgLbl = new Label("Your selection:");// Create the Selection Value LabelLabel selectedValueLbl = new Label();// Bind the value property to the text property of the LabelselectedValueLbl.textProperty().bind(cars.valueProperty());// Display controls in a GridPaneGridPane root = new GridPane();// Set the spacing between columns and rowsroot.setVgap(10);root.setHgap(10);// Add the Labels and the ChoiceBox to the GridPaneroot.addRow(0, carLbl, cars);root.addRow(1, selectionMsgLbl, selectedValueLbl);// Set the Size of the GridPaneroot.setMinSize(350, 250);/*  * Set the padding of the GridPane * Set the border-style of the GridPane * Set the border-width of the GridPane * Set the border-insets of the GridPane * Set the border-radius of the GridPane * Set the border-color of the GridPane*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A ChoiceBox Example");// Display the Stagestage.show();}}

3.9.2 The GUI

After starting the application, the following window appears:

A JavaFX ChoiceBox Example
A ChoiceBox Example before Selection

After selecting an item, the message will be changed:

A JavaFX ChoiceBox Example
A ChoiceBox Example after Selection

3.10 ComboBox

AComboBox is used to let a user select an item from a list of items. You can think ofComboBox as an advanced version ofChoiceBox. AComboBox is highly customizable. TheComboBox class inherits fromComboBoxBase class, which provides the common functionality for all ComboBox-like controls, such asComboBox,ColorPicker, andDatePicker. If you want to create a custom control that will allow users to select an item from a pop-up list, you need to inherit your control from theComboBoxBase class.

3.10.1 The Code

FxComboBoxExample.java

import javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.scene.Scene;import javafx.scene.control.ComboBox;import javafx.scene.control.Label;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxComboBoxExample extends Application{// Create the Selection LabelLabel selectionLbl = new Label("Your selection: None");public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the Label for the CarLabel carLbl = new Label("Car:");// Create a ComboBox for carsComboBox<String> cars = new ComboBox<>();// Add the items to the ComboBoxcars.getItems().addAll("Ford", "Audi", "Ferrari", "Porsche");// Select the first car from the listcars.getSelectionModel().selectFirst();// Add a ChangeListener to the ComboBoxcars.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>(){    public void changed(ObservableValue<? extends String> ov, final String oldValue, final String newValue)     {    selectionLbl.setText("Your selection: " + newValue);    }});// Create the HBoxHBox carbox = new HBox();// Add the children to the HBoxcarbox.getChildren().addAll(carLbl, cars);// Set the vertical spacing between children to 10pxcarbox.setSpacing(10);// Create the VBoxVBox root = new VBox();// Add the children to the VBoxroot.getChildren().addAll(carbox, selectionLbl);// Set the vertical spacing between children to 10pxroot.setSpacing(10);// Set the Size of the VBoxroot.setMinSize(350, 250);/*  * Set the padding of the VBox * Set the border-style of the VBox * Set the border-width of the VBox * Set the border-insets of the VBox * Set the border-radius of the VBox * Set the border-color of the VBox*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A ComboBox Example");// Display the Stagestage.show();}}

3.10.2 The GUI

After starting the application, the following window appears:

A JavaFX ComboBox Example
A ComboBox Example before Selection

After selectang an item, the message will be changed:

A JavaFX ComboBox Example
A ComboBox Example after Selection

3.11 ListView

AListView is used to allow a user to select one item or multiple items from a list of items. Each item inListView is represented by an instance of theListCell class, which can be customized. The items list in aListView may contain any type of objects.ListView is a parameterized class. The parameter type is the type of the items in the list.

3.11.1 The Code

FxListViewExample.java

import javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.ListView;import javafx.scene.layout.GridPane;import javafx.stage.Stage;public class FxListViewExample extends Application{// Create the Selection LabelLabel selectionLbl = new Label("Your selection: None");public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the ListViewListView<String> cars = new ListView<String>();// Add Items to the ListViewcars.getItems().addAll("Ford", "Audi", "Ferrari", "Porsche");// Select the first car from the listcars.getSelectionModel().selectFirst();// Add ChangeListener to the ListViewcars.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>(){    public void changed(ObservableValue<? extends String> ov, final String oldValue, final String newValue)     {    selectionLbl.setText("Your selection: " + newValue);    }});// Create the GridPaneGridPane root = new GridPane();// Set the horizontal and vertical spacing between columns and rowsroot.setVgap(10);root.setHgap(10);// Add ListView and Label to the GridPaneroot.addRow(0, cars);root.addRow(1, selectionLbl);// Set the Size of the GridPaneroot.setMinSize(300, 200);/*  * Set the padding of the GridPane * Set the border-style of the GridPane * Set the border-width of the GridPane * Set the border-insets of the GridPane * Set the border-radius of the GridPane * Set the border-color of the GridPane*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A ListView Example");// Display the Stagestage.show();}}

3.11.2 The GUI

After starting the application, the following window appears:

A JavaFX ListView Example
A ListView Example before Selection

After selecting an item in the list, the message will be changed:

A JavaFX ListView Example
A ListView Example after Selection

3.12 TextArea

ATextArea is a text input control. It inherits from the ATextInputControl class. It lets the user enter multiline plain text. If you need a control to enter a single line of plain text, useTextField instead. If you want to use rich text, use theHTMLEditor control. Unlike theTextField, newline and tab characters in the text are preserved. A newline character starts a new paragraph in aTextArea.

3.12.1 The Code

FxComboBoxExample.java

import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.TextArea;import javafx.scene.control.TextField;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxTextAreaExample extends Application {// Create the Message TextAreaTextArea messageArea = new TextArea();public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the TextField for the Inputfinal TextField input = new TextField();input.setPromptText("Input your message here");// Set the Prompt and Size of the TextAreamessageArea.setPromptText("Your Message:");messageArea.setPrefColumnCount(20);messageArea.setPrefRowCount(10);// Create the Print ButtonButton printBtn = new Button("Print Message");// Add an EvenetHandler to the ButtonprintBtn.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            messageArea.appendText(input.getText()+ "\n");            }        });// Create the VBoxVBox root = new VBox();// Add Labels, TextArea and TextField to the VBoxroot.getChildren().addAll(new Label("Input:"), input, new Label("Messages:"), messageArea, printBtn);// Set the Size of the VBoxroot.setMinSize(350, 250);/*  * Set the padding of the VBox * Set the border-style of the VBox * Set the border-width of the VBox * Set the border-insets of the VBox * Set the border-radius of the VBox * Set the border-color of the VBox*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A TextArea Example");// Display the Stagestage.show();}}

3.12.2 The GUI

After starting the application, the following window appears:

A JavaFX TextArea Example
A TextArea Example before Inserting a Text

After inserting a text in theTextField, theTextArea contains the inserted data:

A JavaFX TextArea Example
A TextArea Example after Inserting a Text

3.13 Menu

AMenu is used to provide a list of actionable items to the user in a compact form. You can also provide the same list of items using a group of buttons, where each button represents an actionable item. It is a matter of preference which one you use: a menu or a group of buttons.

There is a noticeable advantage of a using a menu. It uses much less space on the screen, compared to a group of buttons, by folding (or nesting) the group of items under another item.

For example, if you have used a file editor, the menu items such as New, Open, Save, and Print are nested under a top-level File menu.

A user needs to click the File menu to see the list of items that are available under it. Typically, in cases of a group of buttons, all items are visible to the user all the time, and it is easy for users to know what actions are available. Therefore, there is little tradeoff between the amount of space and usability when you decide to use a menu or buttons. Typically, a menu bar is displayed at the top of a window.

Using amenu is a multistep process. The following sections describe the steps in detail. The following is the summary of steps:

  • 1. Create a menu bar and add it to a container.
  • 2. Create menus and add them to the menu bar.
  • 3. Create menu items and add them to the menus.
  • 4. Add ActionEvent handlers to the menu items to perform actions when they are clicked.

3.13.1 The Code

FxMenuExample.java

import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.Menu;import javafx.scene.control.MenuBar;import javafx.scene.control.MenuItem;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxMenuExample extends Application{// Create the Message LabelLabel messageLbl = new Label("Press any Menu Item to see the message");public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create some menusMenu fileMenu = new Menu("File");Menu editMenu = new Menu("Edit");// Create the MenuItem NewMenuItem newItem = new MenuItem("New");newItem.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have pressed the New Menu Item");            }        });// Create the MenuItem OpenMenuItem openItem = new MenuItem("Open");openItem.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have pressed the Open Menu Item");            }        });// Add menu items to the File menufileMenu.getItems().addAll(newItem, openItem);// Create the MenuItem CopyMenuItem copyItem = new MenuItem("Copy");copyItem.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have pressed the Copy Menu Item");            }        });// Create the MenuItem PasteMenuItem pasteItem = new MenuItem("Paste");pasteItem.setOnAction(new EventHandler<ActionEvent>() {            @Override public void handle(ActionEvent e)             {            printMessage("You have pressed the Paste Menu Item");            }        });// Add menu items to the Edit menueditMenu.getItems().addAll(copyItem, pasteItem);// Create a menu barMenuBar menuBar = new MenuBar();// Add menus to a menu barmenuBar.getMenus().addAll(fileMenu, editMenu);// Create the Menu BoxHBox menu = new HBox();// Add the MenuBar to the Menu Boxmenu.getChildren().add(menuBar);// Create the VBoxVBox root = new VBox();// Add the children to the VBoxroot.getChildren().addAll(menu,messageLbl);// Set the Size of the VBoxroot.setMinSize(350, 250);/*  * Set the padding of the VBox * Set the border-style of the VBox * Set the border-width of the VBox * Set the border-insets of the VBox * Set the border-radius of the VBox * Set the border-color of the VBox*/root.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Menu Example");// Display the Stagestage.show();}// Helper Methodpublic void printMessage(String message){// Set the Text of the LabelmessageLbl.setText(message);}}

3.13.2 Using Menu Bars

A menu bar is a horizontal bar that acts as a container for menus. An instance of theMenuBar class represents a menu bar. You can create aMenuBar using its default constructor:

// Create a menu barMenuBar menuBar = new MenuBar();// Add menus to a menu barmenuBar.getMenus().addAll(fileMenu, editMenu);

3.13.3 Using Menus

A menu contains a list of actionable items, which are displayed on demand, for example, by clicking it. The list of menu items is hidden when the user selects an item or moves the mouse pointer outside the list. A menu is typically added to a menu bar or another menu as a submenu. An instance of theMenu class represents a menu. A menu displays text and a graphic.

// Create some menusMenu fileMenu = new Menu("File");Menu editMenu = new Menu("Edit");

3.13.4 Using Menu Items

AMenuItem represents an actionable option. When it is clicked, the registeredActionEvent handlers are called.

The following snippet of code creates an New MenuItem and adds an ActionEvent handler that prints out the message:

// Create the MenuItem NewMenuItem newItem = new MenuItem("New");newItem.setOnAction(new EventHandler<ActionEvent>() {@Override public void handle(ActionEvent e) {printMessage("You have pressed the New Menu Item");}});

AMenuItem is added to a menu. A menu stores the reference of its items in anObservableList whose reference can be obtained using thegetItems() method:

// Add menu items to the Edit menueditMenu.getItems().addAll(copyItem, pasteItem);

3.13.5 The GUI

After starting the application, the following window appears:

A JavaFX Menu Example
A Menu Example before choosing an Item

After selecting a specificMenuItem, the message will be changed:

A JavaFX Menu Example
A Menu Example after choosing an Item

4. Download Java Source Code

This was a JavaFX tutorial with a short Inroduction and an Example about the most important classes.

Download
You can download the full source code of this tutorial here:JavaFxTutorial.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Andreas PomarolliAndreas PomarolliFebruary 15th, 2016Last Updated: April 24th, 2019
1 3,093 30 minutes read
Photo of Andreas Pomarolli

Andreas Pomarolli

Andreas has graduated from Computer Science and Bioinformatics at the University of Linz. During his studies he has been involved with a large number of research projects ranging from software engineering to data engineering and at least web engineering. His scientific focus includes the areas of software engineering, data engineering, web engineering and project management. He currently works as a software engineer in the IT sector where he is mainly involved with projects based on Java, Databases and Web Technologies.

Related Articles

The JavaFX Print API

July 8th, 2016

JavaFX WebView Example

October 13th, 2016

JavaFX Canvas Example

May 18th, 2016

JavaFX CSS Tutorial

May 5th, 2016

The JavaFX Media API

August 8th, 2016

JavaFX 2D Shape Example

October 21st, 2016
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.