SlideShare a Scribd company logo
DEPARTMENT OF INFORMATION TECHNOLOGY
R2017 - SEMESTER III
CS3391 – OBJECT ORIENTED
PROGRAMMING
UNIT V - JAVAFX EVENT
HANDLING, CONTROLS AND
COMPONENTS
CLASS NOTES
Complimented with
PERSONALIZED LEARNING
MATERIAL (PLM)
With
PERSONALIZED ASSESSMENT
TESTS (PATs)
ction to PERSONALIZED LEARNING MATERIAL (PLM)
The PERSONALIZED LEARNING MATERIAL (PLM) is special Type of
Learning Material designed and developed by Er. K.Khaja Mohideen , Assistant
Professor , Aalim Muhammed Salegh College of Engineering, Avadi-IAF,
Chennai – 600 055, India.
This material called PLM is an innovative Learning Type based Artificial
Intelligence based Suggestive learning Strategy (SLS) that recommends the
selective Topics to Learners of different Learning mind sets groups.
We identified three major such Learner Groups from Subject Learning
Student Communities and are as follows:
1) Smart Learning Groups
2) Effective Learning Groups
3) Slow Learning Groups
The three Coloring depicts the following levels of Experiencing Learners groups:
1) Smart Learning Groups – Greenish Shadow
2) Effective Learning Groups – Orange Shadow
3) Slow Learning Groups – Red Shadow
The following picture illustrates the same:
Note: The decision on PLM Topic grouping type is based on the Designer’s
Academic Experience and his Academic Excellence on the selective Course
Domain.
MOST IMPORTANT IMPORTANT NOT IMPORTANT
PLM with PAT - TASKS TO BE EXECUTED
1) SELECT YOUR TOPIC OF CHOICE
➢ You can choose the Topic of your Interest from the selected
UNIT of the Selected Subject.
2) INTRODUCTION OF SUB-TOPICS
➢ Identify and list the Sub-topics for the above selected main
topic from the selected UNIT of the Selected Subject.
3) KEYWORDS OF SELECTED TOPICS
➢ Continue to identify the Keywords or main key terms of the
above selected main topic from the selected UNIT of the
Selected Subject.
4) FORMING THE KEY STATEMENTS
➢ Form the answer statement(s) from the keyword and justify
the answer framed.
5) TAKE THE PERSONALIZED ASSESSMENT TEST (PAT)
PERSONALIZED ASSESSMENT
TESTS (PATs)
An Introduction to PAT
Personalized Assessment Test(PAT) is a specialized Assessment meant for
different Learners groups of Aalim Muhammed Salegh Salegh College of
Engineering.
The major test type includes:
1) Multiple Choice Question (MCQ) Test(s)
2) Fill in the blank Test(s)
3) Descriptive Question Type Test(s)
NOTE:
The mode of conduct of the PAT Assessment is based on the time and
resource availability.
That is it is either OFF-LINE or ON-LINE mode.
Refer ANNEXTURE – A
FOR
PERSONALIZED
ASSESSMENT TEST (PAT)
INDEX
SL No. Topic PAGE NO.
UNIT – V : Syllabus with PL 05
1 JAVAFX Events and Controls: Event
Basics
06
2 Handling Key and Mouse Events. 10
3 Controls: Checkbox,
12
4 ToggleButton 17
5 RadioButtons 27
6 ListView
32
7 ComboBox 55
8 ChoiceBox 60
9 Text Controls 65
10 ScrollPane. 67
Layouts
– FlowPane – HBox and VBox –
BorderPane – StackPane – GridPane.
Menus – Basics – Menu – Menu bars –
MenuItem.
TAKE :- PERSONALIZED ASSESSMENT TEST (PAT) -I
UNIT – V
UNIT V: JAVAFX EVENT HANDLING, CONTROLS AND
COMPONENTS 9
JAVAFX Events and Controls: Event Basics – Handling Key and Mouse
Events. Controls: Checkbox, ToggleButton – RadioButtons – ListView –
ComboBox – ChoiceBox – Text Controls – ScrollPane. Layouts – FlowPane
– HBox and VBox – BorderPane – StackPane – GridPane. Menus – Basics –
Menu – Menu bars – MenuItem.
NOTE:
➔ Important Topic
→ Less Important
➔ → Not Important
Graphics programming
• Java contains support for graphics that enable programmers to visually enhance
applications.
• Java contains many more sophisticated drawing capabilities as part of the Java 2D
API.
Swing
• Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight
components.
• The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
JAVAFX
JAVAFX Events and Controls
Events: Event Basics – Handling Key and Mouse Events.
Controls: Checkbox, ToggleButton – RadioButtons – ListView – ComboBox –
ChoiceBox – Text Controls
Layouts – ScrollPane - FlowPane – HBox and VBox – BorderPane – StackPane –
GridPane.
Menus – Basics – Menu – Menu bars – MenuItem.
JAVAFX PLATFORM FOR JAVA GUI APPLICATION
DEVELOPMENT
AN OVERVIEW OF JAVA GUI APPLICATION DEVELOPMENT
INTRODUCTION TO JAVAFX
• JavaFX is a software platform for creating and delivering desktop applications, as
well as rich web applications that can run across a wide variety of devices
• This course will get you started with the fundamentals of GUI development using
JavaFX
• Understanding the basics of JavaFX and visualizing the JavaFX structure
• Getting started with JavaFX and creating your first ever GUI using Java. Learning
how to add various elements such as Text, Links, and Buttons to the JavaFX GUI
• Understanding Transactions, Scripting, and Connections in Redis
• Exploring layouts in JavaFX.
JavaFX is a software platform that will be imported from:
import java.javafx.*;
It has the following components:
a) javafx.base
b) javafx.controls
c) javafx.fxml
d) javafx.graphics
e) javafx.media
f) javafx.web
Uses
Students who wish to get hands-on an amazing GUI development framework - JavaFX
Users who wish to learn GUI and desktop application development using Java
Benefits
• JavaFX is based on a scene graph model that is superior to models used by
Java 2D and Swing
• JavaFX performs well
• JavaFX has properties and binding
• You don’t have to abandon your Swing code to begin using JavaFX
• JavaFX Scene Builder is a great tool for creating JavaFX UIs
• JavaFX includes 3D.
1. Event Basics
1.1 Event handling in JAVA
What are the components of event handling?
• An event represents an occurrence of something of interest to the
application, such as a mouse being moved or a key being pressed.
Event handling has three main components
a) Events: An event is a change in state of an object.
b) Events Source: An event source is an object that generates an event.
c) Listeners: A listener is an object that listens to the event. A listener gets
notified when an event occurs.
1.2 Event Handling in JAVAFX
How are events handled in JavaFX?
• In JavaFX applications, events are notifications that something has
happened.
• As a user clicks a button, presses a key, moves a mouse, or performs other
actions, events are dispatched.
• Registered event filters and event handlers within the application receive the
event and provide a response.
• In JavaFX, an event is an instance of the javafx.event.
• Event class or any subclass of Event.
• JavaFX provides several events, including DragEvent, KeyEvent,
MouseEvent, ScrollEvent, and others.
• You can define your own event by extending the Event class.
Event Properties
Every event includes the information described in Table 1-1.
Table 1-1 Event Properties
Property Description
Event
type
Type of event that occurred.
Source Origin of the event, with respect to the location of the event in the event
dispatch chain. The source changes as the event is passed along the chain.
Target Node on which the action occurred and the end node in the event dispatch
chain. The target does not change, however if an event filter consumes the
event during the event capturing phase, the target will not receive the event.
• Event subclasses provide additional information that is specific to the type of
event.
• For example, the MouseEvent class includes information such as which button
was pushed, the number of times the button was pushed, and the position of the
mouse.
Package javafx.event
Provides basic framework for FX events, their delivery and handling.
See: Description
•
Interface Summary
Interface Description
EventDispatchChain Represents a chain of EventDispatcher objects, which can
dispatch an Event.
EventDispatcher An EventDispatcher represents an event dispatching and
processing entity.
EventHandler<T extends Event> Handler for events of a specific class / type.
EventTarget Represents an event target.
•
Class Summary
Class Description
ActionEvent An Event representing some type of action.
Event Base class for FX events.
EventType<T extends Event> This class represents a specific event type associated with an Event.
WeakEventHandler<T extends Event> Used in event handler registration in place of its associated event
handler
Event Types
• An event type is an instance of the EventType class.
• Event types further classify the events of a single event class.
• For example, the KeyEvent class contains the following event types:
• KEY_PRESSED
• KEY_RELEASED
• KEY_TYPED
• Event types are hierarchical. Every event type has a name and a super type.
For example, the name of the event for a key being pressed
is KEY_PRESSED, and the super type is KeyEvent.ANY.
The super type of the top-level event type is null. Figure 1-1 shows a subset of the
hierarchy.
Figure 1-1 Event Type Hierarchy
Description of "Figure 1-1 Event Type Hierarchy"
• The top-level event type in the hierarchy is Event.ROOT, which is equivalent
to Event.ANY.
• In the subtypes, the event type ANY is used to mean any event type in the event
class. For example, to provide the same response to any type of key event,
use KeyEvent.ANY as the event type for the event filter or event handler.
• To respond only when a key is released, use
the KeyEvent.KEY_RELEASED event type for the filter or handler.
Event Targets
• The target of an event can be an instance of any class that implements
the EventTarget interface.
• The implementation of the buildEventDispatchChain creates the event dispatch
chain that the event must travel to reach the target.
• The Window, Scene, and Node classes implement the EventTarget interface and
subclasses of those classes inherit the implementation.
• Therefore, most of the elements in your user interface have their dispatch chain
defined, enabling you to focus on responding to the events and not be concerned
with creating the event dispatch chain.
• If you create a custom UI control that responds to user actions and that control is a
subclass of Window, Scene, or Node, your control is an event target through
inheritance.
• If your control or an element of your control is not a subclass of Window, Scene,
or Node, you must implement the EventTarget interface for that control or
element.
• For example, the MenuBar control is a target through inheritance, but
the MenuItem element of a menu bar must implement the EventTarget interface so
that it can receive events.
Event Delivery Process
The event delivery process contains the following steps:
a) Target selection
b) Route construction
c) Event capturing
d) Event bubbling
a) Target Selection
• When an action occurs, the system determines which node is the target based on
internal rules:
• For key events, the target is the node that has focus.
• For mouse events, the target is the node at the location of the cursor. For
synthesized mouse events, the touch point is considered the location of the cursor.
• For continuous gesture events that are generated by a gesture on a touch screen,
the target is the node at the center point of all touches at the beginning of the
gesture. For indirect gesture events that are generated by a gesture on something
other than a touch screen, such as a trackpad, the target is the node at the location
of the cursor.
• For swipe events that are generated by a swipe on a touch screen, the target is the
node at the center of the entire path of all of the fingers. For indirect swipe events,
the target is the node at the location of the cursor.
• For touch events, the default target for each touch point is the node at the location
first pressed. A different target can be specified using the ungrab(), grab(),
or grab(node) methods for a touch point in an event filter or event handler.
• If more than one node is located at the cursor or touch, the topmost node is
considered the target. For example, if a user clicks or touches the triangle shown
in Figure 1-2, the triangle is the target, not the rectangle that contains the circle
and the triangle.
Figure 1-2 Sample User Interface Event Targets
Description of "Figure 1-2 Sample User Interface Event Targets"
• When a mouse button is pressed and the target is selected, all subsequent mouse
events are delivered to the same target until the button is released.
• Similarly for gesture events, from the start of the gesture to the completion of the
gesture, gesture events are delivered to the target identified at the beginning of the
gesture.
• The default for touch events is to deliver the events to the initial target node that
was identified for each touch point, unless the target is modified using
the ungrab(), grab(), or grab(node) methods.
b) Route Construction
• The initial event route is determined by the event dispatch chain that was created
in the implementation of the buildEventDispatchChain() method of the selected
event target.
• For example, if a user clicks the triangle shown in Figure 1-2, the initial route is
shown by the gray nodes in Figure 1-3. When a scene graph node is selected as an
event target, the initial event route set in the default implementation of
the buildEventDispatchChain() method in the Node class is a path from the stage
to itself.
Figure 1-3 Event Dispatch Chain
Description of "Figure 1-3 Event Dispatch Chain"
The route can be modified as event filters and event handlers along the route process the
event.
Also, if an event filter or event handler consumes the event at any point, some nodes on
the initial route might not receive the event.
c) Event Capturing Phase
• In the event capturing phase, the event is dispatched by the root node of your
application and passed down the event dispatch chain to the target node. Using the
event dispatch chain shown in Figure 1-3, the event travels from the Stage node to
the Triangle node during the event capturing phase.
• If any node in the chain has an event filter registered for the type of event that
occurred, that filter is called. When the filter completes, the event is passed to the
next node down the chain. If a filter is not registered for a node, the event is
passed to the next node down the chain. If no filter consumes the event, the event
target eventually receives and processes the event.
d) Event Bubbling Phase
• After the event target is reached and all registered filters have processed the event,
the event returns along the dispatch chain from the target to the root node.
• Using the event dispatch chain shown in Figure 1-3, the event travels from the
Triangle node to the Stage node during the event bubbling phase.
• If any node in the chain has a handler registered for the type of event encountered,
that handler is called.
• When the handler completes, the event is returned to the next node up the chain.
• If a handler is not registered for a node, the event is returned to the next node up
the chain. If no handler consumes the event, the root node eventually receives the
event and processing is completed.
1.3 Sample JavaFX Application
package yourapplication;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class YourApplication extends Application {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 300, 250);
Button btn = new Button();
btn.setLayoutX(100);
btn.setLayoutY(80);
btn.setText("Hello World");
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
System.out.println("Hello World");
}
});
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.show();
}
}
The "Hello World" code creates a window with a single button.
The setOnAction() method is used to register an event handler that handles the action
events that are dispatched when the button is clicked.
The handle() method in the event handler handles the event by printing the string "Hello
World" to the console.
1.4 Keyboard Events
The Keyboard example demonstrates the following uses of handlers:
a) Registering a single handler for two different event types
b) Providing common event processing for child nodes in a parent node
Figure 4-1 is the screen that is shown when the Keyboard Example is started.
• The user interface consists of four letters, each in its own square, which represent
the corresponding keyboard key.
• The first key on the screen is highlighted, which indicates that it has the focus.
• Use the left and right arrow keys on the keyboard to move the focus to a different
key on the screen.
Figure 4-1 Initial Screen for Keyboard Example
Description of Figure 4-1 follows
Description of "Figure 4-1 Initial Screen for Keyboard Example"
When the Enter key is pressed, the key on the screen with the focus changes to red.
When the Enter key is released, the key on the screen returns to its previous color. When
the key for a letter that matches one of the keys on the screen is pressed, the matching
key on the screen changes to red, and returns to its previous color when the key is
released. When a key that does not match any key on the screen is pressed, nothing
happens. Figure 4-2 shows the screen when the A key has focus and the D key on the
keyboard is pressed.
Figure 4-2 Key Pressed Screen
Description of Figure 4-2 follows
Description of "Figure 4-2 Key Pressed Screen"
Handlers for the Keyboard Example
• In the Keyboard example, internally each key shown on the screen is represented
by a key node. All key nodes are contained in a single keyboard node.
• Each key node has a handler that receives key events when the key has focus.
• The handler responds to the key-pressed and key-released events for the Enter
key by changing the color of the key on the screen.
• The event is then consumed so that the keyboard node, which is the parent node,
does not receive the event.
Example 4-3 shows the installEventHandler() method that defines the handler for the
key nodes.
Example 4-3 Handler for the Key Nodes
private void installEventHandler(final Node keyNode) {
// handler for enter key press / release events, other keys are
// handled by the parent (keyboard) node handler
final EventHandler<KeyEvent> keyEventHandler =
new EventHandler<KeyEvent>() {
public void handle(final KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.ENTER) {
setPressed(keyEvent.getEventType()
== KeyEvent.KEY_PRESSED);
keyEvent.consume();
}
}
};
keyNode.setOnKeyPressed(keyEventHandler);
keyNode.setOnKeyReleased(keyEventHandler);
}
• The keyboard node has two handlers that handle key events that are not consumed
by a key node handler.
• The first handler changes the color of the key node that matches the key pressed.
The second handler responds to the left and right arrow keys and moves the focus.
• Example 4-4 shows the installEventHandler() method that defines the handlers for
the keyboard node.
Example 4-4 Handlers for the Keyboard Node
private void installEventHandler(final Parent keyboardNode) {
// handler for key pressed / released events not handled by
// key nodes
final EventHandler<KeyEvent> keyEventHandler =
new EventHandler<KeyEvent>() {
public void handle(final KeyEvent keyEvent) {
final Key key = lookupKey(keyEvent.getCode());
if (key != null) {
key.setPressed(keyEvent.getEventType()
== KeyEvent.KEY_PRESSED);
keyEvent.consume();
}
}
};
keyboardNode.setOnKeyPressed(keyEventHandler);
keyboardNode.setOnKeyReleased(keyEventHandler);
keyboardNode.addEventHandler(KeyEvent.KEY_PRESSED,
new EventHandler<KeyEvent>() {
public void handle(
final KeyEvent keyEvent) {
handleFocusTraversal(
keyboardNode,
keyEvent);
}
});
}
The two handlers for the key-pressed event are considered peer handlers. Therefore,
even though each handler consumes the event, the other handler is still invoked.
Event handlers for keyboard events include setOnKeyPressed and setOnKeyReleased.
Example 2-3 shows samples of these event handlers.
Example 2-3 Sample Event Handlers for Keyboard Events
final TextField textBox = new TextField();
textBox.setPromptText("Write here");
textBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
System.out.println("Key Pressed: " + ke.getText());
}
});
textBox.setOnKeyReleased(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
System.out.println("Key Released: " + ke.getText());
}
});
2. Handling Key and Mouse Events
2.1 Handling Events
• In JavaFX applications, events are notifications that something has
happened.
• As a user clicks a button, presses a key, moves a mouse, or performs other
actions, events are dispatched.
• Registered event filters and event handlers within the application receive the
event and provide a response.
2.2 Processing Events
• Processing Events describes events and the handling of events in JavaFX
applications, event types, event targets, event capturing, event bubbling, and the
underlying architecture of the event processing system.
• Events are used to notify your application of actions taken by the user and enable
the application to respond to the event.
• The JavaFX platform provides the structure for capturing an event, routing the
event to its target, and enabling the application to handle the event as needed.
Mouse Events
Convenience methods for registering event handlers for mouse events include
setOnMouseEntered, setOnMouseExited, and setOnMousePressed.
The below example shows samples of these event handlers:
Sample Event Handlers for Mouse Events
final Circle circle = new Circle(radius, Color.RED);
circle.setOnMouseEntered(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("Mouse entered");
}
});
circle.setOnMouseExited(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("Mouse exited");
}
});
circle.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("Mouse pressed");
}
});
To see how similar event handlers are used, run the Ensemble sample, which is
available in the JavaFX samples that can be downloaded from the JDK Demos and
Samples section of the Java SE Downloads page.
The Ensemble sample also provides the source code for the event handlers.
Controls:
How JavaFX is designed?
• JavaFX is somewhat inspired by Flash / Flex. Some of the same ideas are found in
JavaFX.
• In general, a JavaFX application contains one or more stages which correspond to
windows. Each stage has a scene attached to it.
• Each scene can have an object graph of controls, layouts etc. attached to it, called
the scene graph.
Here is an illustration of the general structure of a JavaFX application:
Stage
• The stage is the outer frame for a JavaFX application.
• The stage typically corresponds to a window.
• In the early days where JavaFX could run in the browser, the stage could also
refer to the area inside the web page that JavaFX had available to draw itself.
• Since the deprecation of the Java browser plugin JavaFX is mostly used for
desktop applications.
• Here, JavaFX replaces Swing as the recommended desktop GUI framework.
• And I must say, that JavaFX looks a whole lot more consistent and feature rich
than Swing.
• When used in a desktop environment, a JavaFX application can have multiple
windows open. Each window has its own stage.
• Each stage is represented by a Stage object inside a JavaFX application.
• A JavaFX application has a primary Stage object which is created for you by the
JavaFX runtime.
• A JavaFX application can create additional Stage objects if it needs additional
windows open. For instance, for dialogs, wizards etc.
Scene
• To display anything on a stage in a JavaFX application, you need a scene.
• A stage can only show one scene at a time, but it is possible to exchange the scene
at runtime.
• Just like a stage in a theater can be rearranged to show multiple scenes during a
play, a stage object in JavaFX can show multiple scenes (one at a time) during the
life time of a JavaFX application.
• You might wonder why a JavaFX application would ever have more than one
scene per stage. Imagine a computer game.
• A game might have multiple "screens" to show to the user. For instance, an initial
menu screen, the main game screen (where the game is played), a game over
screen and a high score screen.
• Each of these screens can be represented by a different scene.
• When the game needs to change from one screen to the next, it simply attaches the
corresponding scene to the Stage object of the JavaFX application.
• A scene is represented by a Scene object inside a JavaFX application. A JavaFX
application must create all Scene objects it needs.
Scene Graph
• All visual components (controls, layouts etc.) must be attached to a scene to be
displayed, and that scene must be attached to a stage for the whole scene to be
visible.
• The total object graph of all the controls, layouts etc. attached to a scene is called
the scene graph.
Nodes
• All components attached to the scene graph are called nodes.
• All nodes are subclasses of a JavaFX class called javafx.scene.Node .
• There are two types of nodes: Branch nodes and leaf nodes.
• A branch node is a node that can contain other nodes (child nodes).
• Branch nodes are also referred to as parent nodes because they can contain child
nodes.
• A leaf node is a node which cannot contain other nodes.
Controls
• JavaFX controls are JavaFX components which provide some kind of control
functionality inside a JavaFX application.
• For instance, a button, radio button, table, tree etc.
• For a control to be visible it must be attached to the scene graph of
some Scene object.
• Controls are usually nested inside some JavaFX layout component that manages
the layout of controls relative to each other.
JavaFX contains the following controls:
• Accordion
• Button
• CheckBox
• ChoiceBox
• ColorPicker
• ComboBox
• DatePicker
• Label
• ListView
• RadioButton
• Slider
• Spinner
• SplitMenuButton
• SplitPane
• TableView
• TabPane
• TextArea
• TextField
• TitledPane
• ToggleButton
• ToolBar
• TreeTableView
• TreeView
JAVAFX - Controls
BUTTONS CONTROL:
1. Checkbox,
2. ToggleButton
3. RadioButtons
4. ToggleButton
5. RadioButtons
LIST AND COMBO CONTROLS
1. ListView
2. ComboBox
3. ChoiceBox
4. Checkbox
5. ListView
6. ComboBox
Layouts
• JavaFX layouts are components which contains other components inside them.
• The layout component manages the layout of the components nested inside it.
• JavaFX layout components are also sometimes called parent components because
they contain child components, and because layout components are subclasses of
the JavaFX class javafx.scene.Parent.
• A layout component must be attached to the scene graph of some Scene object to
be visible.
JavaFX contains the following layout components:
• Group
• Region
Each of these layout components will be covered in separate texts.
Layouts – ScrollPane - FlowPane – HBox and VBox – BorderPane – StackPane –
GridPane.
• Pane
• HBox
• VBox
• FlowPane
• BorderPane
• StackPane
• TilePane
• GridPane
• AnchorPane
• TextFlow
Nested Layouts
• It is possible to nest layout components inside other layout components.
• This can be useful to achieve a specific layout.
• For instance, to get horizontal rows of components which are not laid out in a
grid, but differently for each row, you can nest multiple HBox layout components
inside a VBox component.
TEXT CONTROLS
JavaFX Text
• The JavaFX Text control can display a text inside a JavaFX GUI.
• The JavaFX Text control is represented by the JavaFX
class javafx.scene.text.Text .
•
• You can set the font to be used by the Text control, text size, font decorations and
many other things.
• Since the JavaFX Text control is a subclass of the JavaFX Shape class, the Text
class has all the same methods available that other JavaFX Shape objects do
- e.g. fill and stroke color and style.
• The JavaFX Text control is also a subclass of the JavaFX Node class,
o so the Text class also has all the same methods available as any other
JavaFX Node has, meaning you can set effects on it etc.
JavaFX Text Example
Here is a simple, complete JavaFX text example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TextExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
Text text = new Text("This is a JavaFX text.");
Scene scene = new Scene(new VBox(text), 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Set Text
You can set the text of a JavaFX Text object via its setText() method.
Here is an example of setting the text of a JavaFX Text control via setText():
Text text = new Text();
text.setText("This is the text to display");
Set Font
You can set the font of a JavaFX Text control via its setFont() method.
Here is an example of setting the font of a JavaFX Text object via its setFont() method:
Text text = new Text("Some Text");
text.setFont(Font.font("Arial"));
This example sets the font to be used by the Text control to render the text to be of the
font family Arial.
The JavaFX Font class used in this example is the javafx.scene.text.Font class.
The Font class actually also lets you specify the font weight and font size.
Here is the example above, modified to also set font weight and font size for the JavaFX
Text control:
Text text = new Text("Some Text");
text.setFont(Font.font("Arial", FontWeight.BOLD, 36));
This example sets the font weight to bold and font size to 36.
The FontWeight class used in this example is the javafx.scene.text.FontWeight class.
Set Fill Color
Being a Shape, you can set the fill color of a JavaFX Text control.
The fill color is the "inside" color used to draw the text.
You set the fill color of a Text control via its setFill() method which takes a JavaFX
Color object as parameter.
Here is an example of setting the fill color of a JavaFX Text control via setFill():
text.setFill(Color.YELLOW);
Set Stroke Color
Being a Shape, you can also set the stroke color of a JavaFX Text control.
The stroke color is the "outline" or "boundary" color used to draw the text.
By default, text is rendered only using the fill color, but setting a stroke color can add a
nice effect.
You set the stroke color of a Text control via its
setStroke() method
which takes a JavaFX Color object as parameter.
Here is an example of setting the stroke color of a JavaFX Text control via setStroke():
text.setStroke(Color.GREEN);
Text X and Y Position
The X and Y position of a JavaFX Text control determines where inside its parent
container element the Text control is displayed - provided the parent container respects
this position (Pane does, VBox does not).
You can set the X and Y position of a Text control via its methods setX() and setY().
Here is an example of setting the X and Y position of a JavaFX Text control:
text.setX(50);
text.setY(25);
Text Origin
The JavaFX Text control has an origin which controls how the text is displayed relative
to the Y position of the Text control. You set the origin using the
Text setTextOrigin() method.
Here is an example of setting the Text origin:
text.setTextOrigin(VPos.BASELINE);
The setTextOrigin() method takes a VPos parameter.
The VPos class contains the following constants you can choose between:
i) VPos.BASELINE
ii) VPos.BOTTOM
iii)VPos.CENTER
iv) VPos.TOP
i) VPos.BASELINE means that the Y position of the Text control is interpreted to mean
the Y baseline of the displayed text.
The text is displayed just above the baseline, with some characters extending below the
baseline.
ii) VPos.BOTTOM means that the Y position of the Text control is interpreted to mean
the bottom the displayed text. This is lower than BASELINE.
iii) VPos.CENTER means that the Y position of the Text control is interpreted to mean
the center of the text vertically.
iv) VPos.TOP means that the Y position of the Text control is interpreted to mean the
top of the text vertically.
Multiline Text
The JavaFX Text control will break the text it displays on to multiple lines based on
these rules:
i) If the text contains a line break ( n ) .
ii) If the text width exceeds a wrapping width set on the Text control.
Here is first an example showing a text that contains a line break:
Text text = new Text("This is a JavaFX text.nLine 2");
The Text control will break the text before "Line" because the String contains a line
break character.
Here is an example of setting a text wrapping width on the JavaFX Text control:
Text text = new Text("This is a longer JavaFX text.");
text.setWrappingWidth(80);
• The JavaFX Text control will attempt to break the text between words.
• Thus, if after a specific word the text width is wider than the wrapping
width,
the Text control will wrap the text before that word that makes the
text wider than the wrapping width.
Text Strikethrough
• The JavaFX Text control enables you to apply a strikethrough decoration to
the text it displays. You enable the strikethrough decoration via the
Text setStrikethrough() method,
passing a value of true as parameter.
A parameter value of false will disable the strikethrough effect.
Here is an example of enabling the JavaFX Text strikethrough decoration via
the setStrikethrough() method:
text.setStrikethrough(true);
Text Underline
The JavaFX Text control enables you to apply an underline decoration to the text it
displays.
You enable the underline decoration via the Text setUnderline() method, passing a value
of true as parameter.
A parameter value of false will disable the underline decoration.
Here is an example of enabling the JavaFX Text underline decoration via
the setUnderline() method:
text.setUnderline(true);
Font Smoothing Techniques
• The JavaFX Text control contains two different font smoothing
(antialiasing) techniques you can choose between.
• The first technique is called LCD, and the second is called GRAY.
• You can choose which font smoothing technique the Text control should use
via the setFontSmoothingType() method.
Here are examples of setting both LCD and GRAY as font smoothing technique on a
JavaFX Text control:
text.setFontSmoothingType(FontSmoothingType.GRAY);
text.setFontSmoothingType(FontSmoothingType.LCD);
Which of the two font smoothing techniques fits best to your application you will have
to experiment with.
JavaFX Fonts
• Create Font Instance
• Using the Font Instance
• List Installed Font Families and Names
Jakob Jenkov
Last update: 2020-11-14
The JavaFX Font class, java.scene.text.Font, enables you to load different Fonts for use in your
JavaFX applications. A font is a text style. All text rendered with the same font will look
similar. In this JavaFX Font tutorial I will show you how to load and set fonts in JavaFX.
Create Font Instance
To use fonts in JavaFX you must create a JavaFX Font instance. The easiest way to create a
JavaFX Font instance is to use the static factory methods in the Font class. The following
example shows how to create JavaFX Font instances using the many variations of the Font
class static factory methods:
String fontFamily = "Arial";
double fontSize = 13;
FontWeight fontWeight = FontWeight.BOLD;
FontPosture fontPosture = FontPosture.ITALIC;
Font font1 = Font.font(fontFamily);
Font font2 = Font.font(fontSize);
Font font3 = Font.font(fontFamily, fontSize);
Font font4 = Font.font(fontFamily, fontWeight , fontSize);
Font font5 = Font.font(fontFamily, fontPosture, fontSize);
Font font6 = Font.font(fontFamily, fontWeight , fontPosture, fontSize);
As you can see, the Font factory methods enable you to create Font instances representing
different font families, font sizes, font weights and font postures.
Using the Font Instance
Once you have created a JavaFX Font instance you use it by setting it on whatever JavaFX
component capable of using a Font. For instance, you can set it on a JavaFX Text control.
Here is an example of setting a Font instance on a Text control:
Font font = Font.font("Arial");
Text text = new Text("This is the text");
text.setFont(font);
Precisely how a Font object is applied to a given JavaFX control depends on the specific
JavaFX control. In the JavaFX Text example the Font object is applied via the
Text setFont() method, as shown above.
List Installed Font Families and Names
The JavaFX Font class provides two methods that can list the font families and font names and
installed on the system the JavaFX application is running on. These methods are
the getFamilies() and getFontNames() methods. Here are some examples of calling these
methods:
List<String> fontFamilies = Font.getFamilies();
List<String> fontNames = Font.getFontNames();
Both font family names and font names can be used when creating a Font instance. Provide
either the font family name or font name in the Font factory method fontFamily parameter.
To see the actual names, loop through the lists above and print out their names, like this:
for(String item : fontFamilies) {
System.out.println(item);
}
for(String item : fontNames) {
System.out.println(item);
}
BUTTONS
JavaFX Button
A JavaFX Button control enables a JavaFX application to have some action executed when the
application user clicks the button. The JavaFX Button control is represented by the
class javafx.scene.control.Button . A JavaFX Button can have a text and an icon on it which
indicate to the user what clicking the button will do.
Creating a Button
You create a button control by creating an instance of the Button class. Here is a
JavaFX Button instantiation example:
Button button = new Button("My Label");
The text to be displayed on the button is passed as parameters to the Button constructor.
Adding a Button to the Scene Graph
For a JavaFX Button to be visible the button object must be added to the scene graph. This
means adding it to a Scene object, or as child of a layout which is attached to a Scene object.
Here is an example that attaches a JavaFX Button to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class ButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
Button button = new Button("My Button");
Scene scene = new Scene(button, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Notice that the Button is added directly to the Scene object. Normally you would nest
the Button inside a layout component of some kind. I have left that out here to keep the
example simple. See the tutorials about layout components to see how they work.
The result of running the above JavaFX Button example is an application that looks like this:
Notice that the button takes up all the space available in the window. That is why it is hard to
see the edges of the button. When a JavaFX button is added to a layout component you can
more easily see the edges of the button.
Button Text
There are two ways to set the text of a JavaFX button. The first way is to pass the text to
the Button constructor. You have already seen this in earlier examples.
The second way to set the button text is by calling the setText() method on the Button instance.
This can be done after the Button instance is created. Thus it can be used to change the text of
a Button that is already visible. Here is an example how how calling setText() on a
JavaFX Button looks:
button.setText("Click me if you dare!");
Button Text Size
You can set the text size of a JavaFX Button. You do so using the CSS property -fx-text-size.
This CSS property is explained in the section about Button CSS Styling
Button Text Wrap
The JavaFX Button control supports text wrapping of the button text. By text wrapping is
meant that if the text is too long to be displayed on a single line inside the button, the text is
broken onto multiple lines.
You enable text wrapping on a JavaFX Button instance using the method setWrapText().
The setWrapText() method takes a single boolean parameter. If you pass a value
of true to setWrapText() then you enable text wrapping. If you pass a value
of false to setWrapText() then you disable text wrapping. Here is an example that enables text
wrapping on a JavaFX button:
button.setWrapText(true);
Here is a screenshot of two JavaFX buttons one of which has text wrapping enabled:
Button Font
You can specify what font the text on a JavaFX Button should be rendered with via
its setFont() method. You can read more about creating fonts in my JavaFX Fonts tutorial.
Here is an example of setting a font on a JavaFX Button:
Button button = new Button("Click me!");
Font font = Font.font("Courier New", FontWeight.BOLD, 36);
button.setFont(font);
Default Button Mode
A JavaFX Button can be set into a default mode. When a Button is in default mode it is
rendered differently, so the user can see that this is the default button. On Windows, the
Button's background color changes, although I guess that also depends on the color theme used
in the application etc. and may change in future versions of JavaFX.
The default button is intended to be used for the "default choice" in a dialog or form. Thus, it
becomes easier for the user to select the choice that the user is most likely making most often.
The default button of a dialog or form has some additional keyboard shortcuts to help the user
click it:
• Windows + Linux
o If no other button has focus, pressing the ENTER keyboard key will activate the
default button.
o If the default button has focus, pressing the ENTER keyboard key will activate
the default button.
• Mac
o Only the default button can be activated by pressing the ENTER keyboard key.
All other buttons are activated by pressing the the SPACE keyboard key.
Setting a JavaFX Button as the default button is done via its setDefaultButton() method. Here is
an example of setting a JavaFX button as default button:
button.setDefaultButton(true);
Cancel Button Mode
A JavaFX Button can be set into cancel mode. When a Button is in cancel mode it can be
activated more easily by pressing the ESC keyboard key - if no other node in the Scene graph
consumes this key press.
Setting a JavaFX Button in cancel mode (as cancel button) is done via
its setCancelButton() method. Here is an example of setting a JavaFX Button in cancel mode:
buttonDefault.setCancelButton(true);
Button Image
It is possible to display an image inside a button next to the button text. The
JavaFX Button class contains a constructor that can take a Node as extra parameter. Here is a
JavaFX label example that adds an image to the button using an JavaFX
ImageView component:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import java.io.FileInputStream;
public class ButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
FileInputStream input = new FileInputStream("resources/images/iconmonstr-home-6-
48.png");
Image image = new Image(input);
ImageView imageView = new ImageView(image);
Button button = new Button("Home", imageView);
Scene scene = new Scene(button, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The result of running the above JavaFX Button example is an application that looks like this:
Button Size
The JavaFX Button class contains a set of methods you can use to set the button size. The
methods controlling the button size are:
button.setMinWidth()
button.setMaxWidth()
button.setPrefWidth()
button.setMinHeight()
button.setMaxHeight()
button.setPrefHeight()
button.setMinSize()
button.setMaxSize()
button.setPrefSize()
The methods setMinWidth() and setMaxWidth() sets the minimum and maximum width the
button should be allowed to have. The method setPrefWidth() sets the preferred width of the
button. When there is space enough to display a button in its preferred width, JavaFX will do
so. If not, JavaFX will scale the button down until it reaches its minimum width.
The methods setMinHeight() and setMaxHeight() sets the minimum and maximum height the
button should be allowed to have. The method setPrefHeight() sets the preferred height of the
button. When there is space enough to display a button in its preferred height, JavaFX will do
so. If not, JavaFX will scale the button down until it reaches its minimum height.
The methods setMinSize(), setMaxSize() and setPrefSize() sets both width and height for the
button in a single call. Thus, these methods takes both a width and a height parameter. For
instance, calling
button.setMaxSize(100, 200);
is equivalent to calling
button.setMaxWidth(100);
button.setMaxHeight(200);
Here is a screenshot of two JavaFX buttons. The first button has the default size calculated
from its button text and the layout component it is nested inside. The second button has a
preferred width of 200 and height of 48 set on it:
Button Events
In order to respond to the click of a button you need to attach an event listener to
the Button object. Here is how that looks:
button.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent actionEvent) {
//... do something in here.
}
});
Here is how attaching a click event listener looks with a Java Lambda expression:
button.setOnAction(actionEvent -> {
//... do something in here.
});
Finally, let us see a full example that changes the text of a JavaFX Label when the button is
clicked:
package com.jenkov.javafx.controls;
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.stage.Stage;
public class ButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
Label label = new Label("Not clicked");
Button button = new Button("Click");
button.setOnAction(value -> {
label.setText("Clicked!");
});
HBox hbox = new HBox(button, label);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Button Mnemonic
You can set a mnemonic on a JavaFX Button instance. A mnemonic is a keyboard key which
activates the button when pressed in conjunction with the ALT key. Thus, a mnemonic is a
keyboard shortcut to activating the button. I will explain how to activate a button via its
mnemonic later.
The mnemonic for a button is specified inside the button text. You mark which key is to be
used as mnemonic by placing an underscore character (_) in front of the character in the button
text you want to set as mnemonic for that button. The underscore character will not be
displayed in the button text. Here is an example setting a mnemonic for a button:
button.setMnemonicParsing(true);
button.setText("_Click");
Notice that it is necessary to first call setMnemonicParsing() on the button with a value of true.
This instructs the button to parse mnemonics in the button text. If you call this method with a
value of false instead, the underscore character in the button text will just show up as text, and
will not be interpreted as a mnemonic.
The second line sets the text _Click on the button. This tells the button to use the key c as
mnemonic. Mnemonics are case insensitive, so it does not have to be an a uppercase C that
activates the button.
To activate the button you can now press ALT-C (both at the same time). That will activate the
button just as if you had clicked it with the mouse.
You can also first press the ALT key once. That will show the mnemonic of the button in the
button text. You can then press the c key. If you press ALT and then ALT again, the mnemonic
is first shown, then hidden again. When the mnemonic is visible you can activate the button
with the mnemonic key alone, without ALT pressed at the same time. When the mnemonic is
not visible you have to press both ALT and the mnemonic key at the same time to activate the
button.
Here are two screenshots showing what it looks like when the mnemonic is invisible and
visible:
Button CSS Styles
You can style a JavaFX button using CSS styles. The JavaFX Button control supports the
following CSS styles:
-fx-border-width
-fx-border-color
-fx-background-color
-fx-font-size
-fx-text-fill
Here is an example setting the background color of a JavaFX button to red:
Button button = new Button("My Button");
button.setStyle("-fx-background-color: #ff0000; ");
This example sets the style directly on the button via the setStyle() method, but you can also
style a JavaFX button via style sheets. See my JavaFX CSS Styling tutorial for more
information about using CSS stylesheets with JavaFX.
Here is a JavaFX button example which creates 4 different buttons. Each button has a CSS style
set on them. After the code example I have included a screenshot of how the buttons look with
the given styling.
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Button Experiment 1");
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");
Button button4 = new Button("Button 4");
button1.setStyle("-fx-border-color: #ff0000; -fx-border-width: 5px;");
button2.setStyle("-fx-background-color: #00ff00");
button3.setStyle("-fx-font-size: 2em; ");
button4.setStyle("-fx-text-fill: #0000ff");
HBox hbox = new HBox(button1, button2, button3, button4);
Scene scene = new Scene(hbox, 400, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Here is a screenshot of the 4 JavaFX buttons with their CSS styling:
The first button has both the -fx-border-width and -fx-border-color CSS properties set. This
results in a 5 pixel wide red border for the button.
The second button has the -fx-background-color CSS property set. This results in a green
background color for the button.
The third button has the -fx-font-size CSS property set. This results in a button with a text that
is 2 times as big as normal.
The fourth button has the -fx-text-fill CSS property set. This results in a button with a blue text
color.
You can combine the CSS styles for a JavaFX button simply by setting multiple CSS properties
on it, like the first button in the example above has.
Disable Button
You can disable a JavaFX Button via its setDisable() method. The setDisable() method takes
a boolean parameter which specify if the button should be disabled or not. A value
of true means the button will be disabled, and a value of false means it will not be disabled -
which means enabled. Here is an example of disabling a JavaFX Button via
its setDisable() method:
Button button = new Button();
button.setText("Click me!");
// here the app is running, and something happens so
// the button should now be disabled.
button.setDisable(true);
// again the app runs, and something happens so
// the button should now be enabled again.
button.setDisable(false);
Button FXML
It is possible to declare a JavaFX Button inside a JavaFX FXML file. I will not explain FXML
in every detail here. Click on the link in the first sentence to read more about how FXML
works. I will just show you the parts of FXML related to the JavaFX Button control. Here is a
very simple FXML file example that shows how to declare a Button:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Button?>
<VBox xmlns:fx="http://javafx.com/fxml" spacing="20">
<children>
<Button fx:id="button1" text="Click me!" onAction="#buttonClicked"/>
</children>
</VBox>
It is the <Button> element that declares the Button control. The fx:id attribute can be used to
wire up the declared Button to a Button member variable inside an FXML Controller object.
The text attribute is used to set the corresponding text property value in the Button instance
created for this Button declaration. That is the text displayed on the button.
The onAction attribute is used to link the Button's onAction event to a method in the FXML
controller object. In this example it is the method named buttonClicked() in the FXML
controller.
Here is how the corresponding FXML controller object's class looks. Notice the name of
the button1 Button member variable matches the fx:id attribute value in the FXML file. This
member variable must be public, by the way. Notice also the method buttonClicked() which is
referenced from the Button onAction attribute in the FXML file.
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
public class ButtonFXMLController {
public Button button1 = null;
private int button1ClickCount = 0;
@FXML
public void buttonClicked(Event e){
this.button1ClickCount++;
String text = "Button1 clicked " + this.button1ClickCount + " times";
System.out.println(text);
button1.setText(text);
}
}
And here is the full JavaFX app that loads the FXML file and creates the FXML controller etc.
:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.File;
import java.net.URL;
public class ButtonFXMLExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader();
ButtonFXMLController controller = new ButtonFXMLController();
loader.setController(controller);
File fxmlFile = new File("assets/fxml/button-example.fxml");
URL fxmlUrl = fxmlFile.toURI().toURL();
loader.setLocation(fxmlUrl);
VBox vbox = loader.<VBox>load();
Scene scene = new Scene(vbox);
primaryStage.setScene(scene);
primaryStage.setTitle("Button FXML Example");
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.show();
}
}
Button Transformations
You can add JavaFX transformations to a JavaFX Button such as scaling, rotation, translation
etc. You add transformation objects to a JavaFX Button like this:
button.getTransforms().add(scaleTransformation);
Here is a full example of adding a Scale transformation to a JavaFX Button:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
public class ButtonTransformationExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Button button = new Button();
button.setText("Click me!");
button.setOnAction((event) -> {
System.out.println("Button clicked!");
});
Scale scaleTransformation = new Scale();
scaleTransformation.setX(3.0);
scaleTransformation.setY(2.0);
scaleTransformation.setPivotX(0);
scaleTransformation.setPivotY(0);
button.getTransforms().add(scaleTransformation);
VBox vbox = new VBox(button);
Scene scene = new Scene(vbox);
primaryStage.setScene(scene);
primaryStage.setWidth(512);
primaryStage.setHeight(256);
primaryStage.show();
}
}
JavaFX ToggleButton
A JavaFX ToggleButton is a button that can be selected or not selected. Like a
button that stays in when you press it, and when you press it the next time it comes
out again. Toggled - not toggled. The JavaFX ToggleButton is represented by the
class javafx.scene.control.ToggleButton .
Creating a ToggleButton
You create a JavaFX ToggleButton by creating an instance of
the ToggleButton class. Here is an example of creating a
JavaFX ToggleButton instance:
ToggleButton toggleButton1 = new ToggleButton("Left");
This example creates a ToggleButton with the text Left on.
Adding a ToggleButton to the Scene Graph
To make a ToggleButton visible you must add it to the JavaFX scene graph. This
means adding it to a Scene, or as child of a layout which is attached to
a Scene object.
Here is an example that attaches a JavaFX ToggleButton to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ToggleButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
ToggleButton toggleButton1 = new ToggleButton("Left");
HBox hbox = new HBox(toggleButton1);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from running the above example code is illustrated in the
following two screenshots. The first screenshot shows a ToggleButton which is not
pressed, and the second screenshot shows the same ToggleButton pressed
(selected, activated etc.):
ToggleButton Text
You can set or change the text of a JavaFX ToggleButton via its setText() method.
Here is an example of changing the text of a JavaFX ToggleButton via setText():
ToggleButton toggleButton = new ToggleButton("Toggle This!");
toggleButton.setText("New Text");
ToggleButton Font
You can set the font to use to render the button text of a JavaFX ToggleButton via
its setFont() method. You can read more about creating fonts in my JavaFX
Fonts tutorial. Here is an example of setting the font of a JavaFX ToggleButton:
ToggleButton toggleButton = new ToggleButton("Toggle This!");
Font arialFontBold36 = Font.font("Arial", FontWeight.BOLD, 36);
toggleButton.setFont(arialFontBold36);
Reading Selected State
The ToggleButton class has a method named isSelected which lets you determine if
the ToggleButton is selected (pressed) or not. The isSelected() method returns
a boolean with the value true if the ToggleButton is selected, and false if not. Here is
an example:
boolean isSelected = toggleButton1.isSelected();
ToggleGroup
You can group JavaFX ToggleButton instances into a ToggleGroup.
A ToggleGroup allows at most one ToggleButton to be toggled (pressed) at any time.
The ToggleButton instances in a ToggleGroup thus functions similarly to radio buttons.
Here is a JavaFX ToggleGroup example:
ToggleButton toggleButton1 = new ToggleButton("Left");
ToggleButton toggleButton2 = new ToggleButton("Right");
ToggleButton toggleButton3 = new ToggleButton("Up");
ToggleButton toggleButton4 = new ToggleButton("Down");
ToggleGroup toggleGroup = new ToggleGroup();
toggleButton1.setToggleGroup(toggleGroup);
toggleButton2.setToggleGroup(toggleGroup);
toggleButton3.setToggleGroup(toggleGroup);
toggleButton4.setToggleGroup(toggleGroup);
Here is a full example that adds the 4 ToggleButton instances to a ToggleGroup, and
adds them to the scene graph too:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ToggleButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
ToggleButton toggleButton1 = new ToggleButton("Left");
ToggleButton toggleButton2 = new ToggleButton("Right");
ToggleButton toggleButton3 = new ToggleButton("Up");
ToggleButton toggleButton4 = new ToggleButton("Down");
ToggleGroup toggleGroup = new ToggleGroup();
toggleButton1.setToggleGroup(toggleGroup);
toggleButton2.setToggleGroup(toggleGroup);
toggleButton3.setToggleGroup(toggleGroup);
toggleButton4.setToggleGroup(toggleGroup);
HBox hbox = new HBox(toggleButton1, toggleButton2, toggleButton3,
toggleButton4);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The resulting applications looks like this:
Reading Selected State of a ToggleGroup
You can read which ToggleButton of a ToggleGroup is selected (pressed) using
the getSelectedToggle() method, like this:
ToggleButton selectedToggleButton =
(ToggleButton) toggleGroup.getSelectedToggle();
If no ToggleButton is selected the getSelectedToggle() method returns null .
JavaFX RadioButton
A JavaFX RadioButton is a button that can be selected or not selected.
The RadioButton is very similar to the JavaFX ToggleButton, but with the difference
that a RadioButton cannot be "unselected" once selected. If RadioButtons are part of
a ToggleGroup then once a RadioButton has been selected for the first time, there
must be one RadioButton selected in the ToggleGroup .
The JavaFX RadioButton is represented by the
class javafx.scene.control.RadioButton. The RadioButton class is a subclass of
the ToggleButton class.
Creating a RadioButton
You create a JavaFX RadioButton using its constructor. Here is a
JavaFX RadioButton instantiation example:
RadioButton radioButton1 = new RadioButton("Left");
The String passed as parameter to the RadioButton constructor is displayed next to
the RadioButton.
Adding a RadioButton to the Scene Graph
To make a RadioButton visible you must add it to the scene graph of your JavaFX
application. This means adding the RadioButton to a Scene, or as child of a layout
which is attached to a Scene object.
Here is an example that attaches a JavaFX RadioButton to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class RadioButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
RadioButton radioButton1 = new RadioButton("Left");
HBox hbox = new HBox(radioButton1);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from running this example looks like this:
Reading Selected State
The RadioButton class has a method named isSelected which lets you determine if
the RadioButton is selected or not. The isSelected() method returns a boolean with
the value true if the RadioButton is selected, and false if not. Here is an example:
boolean isSelected = radioButton1.isSelected();
ToggleGroup
You can group JavaFX RadioButton instances into a ToggleGroup.
A ToggleGroup allows at most one RadioButton to be selected at any time.
Here is a JavaFX ToggleGroup example:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class RadioButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
RadioButton radioButton1 = new RadioButton("Left");
RadioButton radioButton2 = new RadioButton("Right");
RadioButton radioButton3 = new RadioButton("Up");
RadioButton radioButton4 = new RadioButton("Down");
ToggleGroup radioGroup = new ToggleGroup();
radioButton1.setToggleGroup(radioGroup);
radioButton2.setToggleGroup(radioGroup);
radioButton3.setToggleGroup(radioGroup);
radioButton4.setToggleGroup(radioGroup);
HBox hbox = new HBox(radioButton1, radioButton2, radioButton3,
radioButton4);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from running this example looks like this:
Reading Selected State of a ToggleGroup
You can read which RadioButton of a ToggleGroup is selected using
the getSelectedToggle() method, like this:
RadioButton selectedRadioButton =
(RadioButton) toggleGroup.getSelectedToggle();
If no RadioButton is selected the getSelectedToggle() method returns null .
Draggable Panels Example
The Draggable Panels example demonstrates the following uses of filters:
• Registering a filter for a super-type event to provide common handling for subtype events
• Consuming an event to prevent a child node from acting on it
Figure 3-1 is the screen that is shown when the Draggable Panels example is started. The user interface consists of three
panels. Each panel contains different UI controls. At the bottom of the screen is a check box that controls whether the panels
can be dragged.
Figure 3-1 Initial Screen for the Draggable Panels Example
Description of "Figure 3-1 Initial Screen for the Draggable Panels Example"
If the check box is not selected, clicking any of the controls in the panels generates a response from the control. If the check
box is selected, the individual controls do not respond to mouse clicks. Instead, clicking anywhere within a panel and
dragging the mouse moves the entire panel, enabling you to change the position of the panels as shown in Figure 3-2.
Figure 3-2 Screen with Repositioned Panels
Description of "Figure 3-2 Screen with Repositioned Panels"
Filters for the Draggable Panels Example
In the Draggable Panels example, the makeDraggable() method is used in the creation of the three panels to make each
panel movable. This method and the filter definitions are shown in Example 3-3.
Example 3-3 Filter Definitions in makeDraggable()
private Node makeDraggable(final Node node) {
final DragContext dragContext = new DragContext();
final Group wrapGroup = new Group(node);
wrapGroup.addEventFilter(
MouseEvent.ANY,
new EventHandler<MouseEvent>() {
public void handle(final MouseEvent mouseEvent) {
if (dragModeActiveProperty.get()) {
// disable mouse events for all children
mouseEvent.consume();
}
}
});
wrapGroup.addEventFilter(
MouseEvent.MOUSE_PRESSED,
new EventHandler<MouseEvent>() {
public void handle(final MouseEvent mouseEvent) {
if (dragModeActiveProperty.get()) {
// remember initial mouse cursor coordinates
// and node position
dragContext.mouseAnchorX = mouseEvent.getX();
dragContext.mouseAnchorY = mouseEvent.getY();
dragContext.initialTranslateX =
node.getTranslateX();
dragContext.initialTranslateY =
node.getTranslateY();
}
}
});
wrapGroup.addEventFilter(
MouseEvent.MOUSE_DRAGGED,
new EventHandler<MouseEvent>() {
public void handle(final MouseEvent mouseEvent) {
if (dragModeActiveProperty.get()) {
// shift node from its initial position by delta
// calculated from mouse cursor movement
node.setTranslateX(
dragContext.initialTranslateX
+ mouseEvent.getX()
- dragContext.mouseAnchorX);
node.setTranslateY(
dragContext.initialTranslateY
+ mouseEvent.getY()
- dragContext.mouseAnchorY);
}
}
});
return wrapGroup;
}
Filters for the following events are defined and registered for each panel:
• MouseEvent.ANY. This filter processes all mouse events for the panel. If the Drag Mode check box is selected, the filter
consumes the event, and the child nodes, which are the UI controls within the panel, do not receive the event. If the check
box is not selected, the control at the location of the mouse cursor processes the event.
• MouseEvent.MOUSE_PRESSED. This filter processes only mouse-pressed events for the panel. If the Drag Mode check
box is selected, the current location of the mouse is stored.
• MouseEvent.MOUSE_DRAGGED. This filter processes only mouse-dragged events for the panel. If the Drag Mode check
box is selected, the panel is moved.
Note that a panel has three registered filters. Filters for specific event types are invoked before super-type events, so the
filters for MouseEvent.MOUSE_PRESSED and MouseEvent.MOUSE_DRAGGED are invoked before the filter
for MouseEvent.ANY.
JavaFX CheckBox
A JavaFX CheckBox is a button which can be in three different states: Selected,
not selected and unknown (indeterminate). The JavaFX CheckBox control is
represented by the class javafx.scene.control.CheckBox.
Creating a CheckBox
You create a JavaFX CheckBox control via the CheckBox constructor. Here is a
JavaFX CheckBox instantiation example:
CheckBox checkBox1 = new CheckBox("Green");
The String passed to the CheckBox constructor is displayed next to
the CheckBox control.
Adding a CheckBox to the Scene Graph
To make a JavaFX CheckBox control visible you must add it to the scene graph of
your JavaFX application. That means adding the CheckBox control to a Scene object,
or to some layout component which is itself added to a Scene object.
Here is an example showing how to add a CheckBox to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class CheckBoxExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("CheckBox Experiment 1");
CheckBox checkBox1 = new CheckBox("Green");
HBox hbox = new HBox(checkBox1);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from running this code looks like this:
Reading Selected State
You can read the selected state of a CheckBox via its method isSelected(). Here is
an example of how calling isSelected() looks:
boolean isSelected = checkBox1.isSelected();
Allowing Indeterminate State
As mentioned earlier a JavaFX CheckBox can be in an indeterminate state which
means that is is neither selected, nor not selected. The user simply has not
interacted with the CheckBox yet.
By default a CheckBox is not allowed to be in the indeterminate state. You can set if
a CheckBox is allowed to be in an indeterminate state using the
method setAllowIndeterminate(). Here is an example of allowing the indeterminate
state for a CheckBox:
checkBox1.setAllowIndeterminate(true);
Reading Indeterminate State
You can read if a CheckBox is in the indeterminate state via
its isIndeterminate() method. Here is an example of checking if a CheckBox is in the
indeterminate state:
boolean isIndeterminate = checkBox1.isIndeterminate();
Note, that if a CheckBox is not in the indeterminate state, it is either selected or not
selected, which can be seen via its isSelected() method
JavaFX ChoiceBox
The JavaFX ChoiceBox control enables users to choose an option from a
predefined list of choices. The JavaFX ChoiceBox control is represented by the
class javafx.scene.control.ChoiceBox . This JavaFX ChoiceBox tutorial will explain
how to use the ChoiceBox class.
Creating a ChoiceBox
You create a ChoiceBox simply by creating a new instance of the ChoiceBox class.
Here is a JavaFX ChoiceBox instantiation example:
ChoiceBox choiceBox = new ChoiceBox();
Adding Choices to a ChoiceBox
You can add choices to a ChoiceBox by obtaining its item collection and add items to
it. Here is an example that adds choices to a JavaFX ChoiceBox :
choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");
Adding a ChoiceBox to the Scene Graph
To make a ChoiceBox visible you must add it to the scene graph. This means that
you must add the ChoiceBox to a Scene object or to some layout component which is
then attached to the Scene object.
Here is an example showing how to add a JavaFX ChoiceBox to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ChoiceBoxExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ChoiceBox Experiment 1");
ChoiceBox choiceBox = new ChoiceBox();
choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");
HBox hbox = new HBox(choiceBox);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from running this example would look similar to this:
Reading the Selected Value
You can read the selected value of a ChoiceBox via its getValue() method. If no
choice is selected, the getValue() method returns null. Here is an example of
calling getValue():
String value = (String) choiceBox.getValue();
Listening for Selection
It is possible to listen for selection changes in a JavaFX ChoiceBox by setting an
action listener on the ChoiceBox via its setOnAction() method. Here is an example
of setting an action listener on a ChoiceBox which reads what value was selected
in the ChoiceBox:
ChoiceBox choiceBox = new ChoiceBox();
choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");
choiceBox.setOnAction((event) -> {
int selectedIndex = choiceBox.getSelectionModel().getSelectedIndex();
Object selectedItem = choiceBox.getSelectionModel().getSelectedItem();
System.out.println("Selection made: [" + selectedIndex + "] " + selectedItem);
System.out.println(" ChoiceBox.getValue(): " + choiceBox.getValue());
});
JavaFX ComboBox
The JavaFX ComboBox control enables users to choose an option from a
predefined list of choices, or type in another value if none of the predefined choices
matches what the user want to select. The JavaFX ComboBox control is
represented by the class javafx.scene.control.ComboBox . This JavaFX ComboBox
tutorial will explain how to use the ComboBox class.
Creating a ComboBox
You create a ComboBox simply by creating a new instance of the ComboBox class. Here
is a JavaFX ComboBox instantiation example:
ComboBox comboBox = new ComboBox();
Adding Choices to a ComboBox
You can add choices to a ComboBox by obtaining its item collection and add items to
it. Here is an example that adds choices to a JavaFX ComboBox :
comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
Adding a ComboBox to the Scene Graph
To make a ComboBox visible you must add it to the scene graph. This means that you
must add the ComboBox to a Scene object or to some layout component which is then
attached to the Scene object.
Here is an example showing how to add a JavaFX ComboBox to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ComboBoxExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ComboBox Experiment 1");
ComboBox comboBox = new ComboBox();
comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
HBox hbox = new HBox(comboBox);
Scene scene = new Scene(hbox, 200, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from running this example would look similar to this:
Making the ComboBox Editable
A ComboBox is not editable by default. That means, that by default the user cannot
enter anything themselves, but only choose from the predefined list of options. To
make a ComboBox editable you must call the setEditable() method of the ComboBox.
Here is an example making a JavaFX ComboBox editable:
comboBox.setEditable(true);
Once the ComboBox is editable the user can type in values into the ComboBox. The
entered value is also read via the getValue() method as explained earlier. The
following screenthot shows a JavaFX ComboBox which is editable, and with a custom
value entered:
Reading the Selected Value
You can read the selected value of a ComboBox via its getValue() method. If no choice
is selected, the getValue() method returns null. Here is an example of
calling getValue():
String value = (String) comboBox.getValue();
Listening for Selection
It is possible to listen for selection changes in a JavaFX ComboBox by setting an
action listener on the ComboBox via its setOnAction() method. Here is an example
of setting an action listener on a ComboBox which reads what value was selected
in the ComboBox:
ComboBox comboBox = new ComboBox();
comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
comboBox.setOnAction((event) -> {
int selectedIndex = comboBox.getSelectionModel().getSelectedIndex();
Object selectedItem = comboBox.getSelectionModel().getSelectedItem();
System.out.println("Selection made: [" + selectedIndex + "] " + selectedItem);
System.out.println(" ComboBox.getValue(): " + comboBox.getValue());
});
JavaFX ListView
The JavaFX ListView control enables users to choose one or more options from a
predefined list of choices. The JavaFX ListView control is represented by the
class javafx.scene.control.ListView . This JavaFX ListView tutorial will explain how
to use the ListView class.
Creating a ListView
You create a ListView simply by creating a new instance of the ListView class. Here
is a JavaFX ListView instantiation example:
ListView listView = new ListView();
Adding Items to a ListView
You can add items (options) to a ListView by obtaining its item collection and add
items to it. Here is an example that adds items to a JavaFX ListView :
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
Adding a ListView to the Scene Graph
To make a ListView visible you must add it to the scene graph. This means that you
must add the ListView to a Scene object or to some layout component which is then
attached to the Scene object.
Here is an example showing how to add a JavaFX ListView to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ListViewExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");
ListView listView = new ListView();
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
HBox hbox = new HBox(listView);
Scene scene = new Scene(hbox, 300, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from running this example would look similar to this
screenshot:
Notice how the ListView shows multiple options by default. You can set a height
and width for a ListView, but you cannot set explicitly how many items should be
visible. The height determines that based on the height of each item displayed.
If there are more items in the ListView than can fit into its visiible area,
the ListView will add scroll bars so the user can scroll up and down over the items.
Reading the Selected Value
You can read the selected indexes of a ListView via its SelectionModel. Here is an
example showing how to read the selected indexes of a JavaFX ListView:
ObservableList selectedIndices =
listView.getSelectionModel().getSelectedIndices();
The OberservableList will contain Integer objects representing the indexes of the
selected items in the ListView.
Here is a full JavaFX example with a button added which reads the selected items
of the ListView when clicked:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ListViewExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");
ListView listView = new ListView();
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
Button button = new Button("Read Selected Value");
button.setOnAction(event -> {
ObservableList selectedIndices =
listView.getSelectionModel().getSelectedIndices();
for(Object o : selectedIndices){
System.out.println("o = " + o + " (" + o.getClass() + ")");
}
});
VBox vBox = new VBox(listView, button);
Scene scene = new Scene(vBox, 300, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Allowing Multiple Items to be Selected
To allow multiple items in the ListView to be selected you need to set the
corresponding selection mode on the ListView selection model. Here is an example
of setting the selection mode on the JavaFX ListView:
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
Once you have set the SelectionMode.MULTIPLE on the ListView selection model, the
user can select multiple items in the ListView by holding down SHIFT or CTRL
when selecting additional items after the first selected item.
Here is a full JavaFX example that shows how to set a ListView into multiple
selection mode, including a button which when clicked will write out the indices of
the selected items in the ListView :
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ListViewExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");
ListView listView = new ListView();
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
Button button = new Button("Read Selected Value");
button.setOnAction(event -> {
ObservableList selectedIndices =
listView.getSelectionModel().getSelectedIndices();
for(Object o : selectedIndices){
System.out.println("o = " + o + " (" + o.getClass() + ")");
}
});
VBox vBox = new VBox(listView, button);
Scene scene = new Scene(vBox, 300, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
JavaFX TextField
A JavaFX TextField control enables users of a JavaFX application to enter text
which can then be read by the application. The JavaFX TextField control is
represented by the class javafx.scene.control.TextField .
Creating a TextField
You create a TextField control by creating an instance of the TextField class. Here
is a JavaFX TextField instantiation example:
TextField textField = new TextField();
Adding a TextField to the Scene Graph
For a JavaFX TextField to be visible the TextField object must be added to the
scene graph. This means adding it to a Scene object, or as child of a layout which is
attached to a Scene object.
Here is an example that attaches a JavaFX TextField to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class TextFieldExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
TextField textField = new TextField();
HBox hbox = new HBox(textField);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The result of running the above JavaFX TextField example is an application that
looks like this:
Getting the Text of a TextField
You can get the text entered into a TextField using its getText() method which
returns a String. Here is a full example that shows a TextField and a Button and
which reads the text entered into the TextField when the button is clicked:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class TextFieldExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
TextField textField = new TextField();
Button button = new Button("Click to get text");
button.setOnAction(action -> {
System.out.println(textField.getText());
});
HBox hbox = new HBox(textField, button);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Setting the Text of a TextField
You can set the text of a TextField using its setText() method. This is often useful
when you need to set the initial value for at text field that is part of a form. For
instance, editing an existing object or record. Here is a simple example of setting
the text of a JavaFX TextField:
textField.setText("Initial value");
JavaFX PasswordField
• Creating a PasswordField
• Adding a PasswordField to the Scene Graph
• Getting the Text of a PasswordField
Jakob Jenkov
Last update: 2016-05-19
A JavaFX PasswordField control enables users of a JavaFX application to enter
password which can then be read by the application. The PasswordField control
does not show the texted entered into it. Instead it shows a circle for each character
entered. The JavaFX PasswordField control is represented by the
class javafx.scene.control.PasswordField .
Creating a PasswordField
You create a PasswordField control by creating an instance of
the PasswordField class. Here is a JavaFX PasswordField instantiation example:
PasswordField passwordField = new PasswordField();
Adding a PasswordField to the Scene Graph
For a JavaFX PasswordField to be visible the PasswordField object must be added to
the scene graph. This means adding it to a Scene object, or as child of a layout
which is attached to a Scene object.
Here is an example that attaches a JavaFX PasswordField to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class PasswordFieldExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("PasswordField Experiment 1");
PasswordField passwordField = new PasswordField();
HBox hbox = new HBox(passwordField);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The result of running the above JavaFX PasswordField example is an application
that looks like this:
Getting the Text of a PasswordField
You can get the text entered into a PasswordField using its getText() method which
returns a String. Here is a full example that shows a PasswordField and a Button and
which reads the text entered into the PasswordField when the button is clicked:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class PasswordFieldExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("PasswordField Experiment 1");
PasswordField passwordField = new PasswordField();
Button button = new Button("Click to get password");
button.setOnAction(action -> {
System.out.println(passwordField.getText());
});
HBox hbox = new HBox(passwordField, button);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
JavaFX TextArea
JavaFX TextArea control enables users of a JavaFX application to enter text
spanning multiple lines, which can then be read by the application. The JavaFX
TextArea control is represented by the class javafx.scene.control.TextArea .
Creating a TextArea
You create a TextArea control by creating an instance of the TextArea class. Here is
a JavaFX TextArea instantiation example:
TextArea textArea = new TextArea();
Adding a TextArea to the Scene Graph
For a JavaFX TextArea to be visible the TextArea object must be added to the scene
graph. This means adding it to a Scene object, or as child of a layout which is
attached to a Scene object.
Here is an example that attaches a JavaFX TextArea to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextAreaExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("TextArea Experiment 1");
TextArea textArea = new TextArea();
VBox vbox = new VBox(textArea);
Scene scene = new Scene(vbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The result of running the above JavaFX TextArea example is an application that
looks like this:
Reading the Text of a TextArea
You can read the text entered into a TextArea via its getText() method. Here is an
example of reading text of a JavaFX TextArea control via its getText() method:
String text = textArea.getText();
Here is a full example that shows a TextArea and a Button and which reads the text
entered into the TextArea when the button is clicked:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextAreaExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("TextArea Experiment 1");
TextArea textArea = new TextArea();
Button button = new Button("Click to get text");
button.setMinWidth(50);
button.setOnAction(action -> {
System.out.println(textArea.getText());
textArea.setText("Clicked!");
});
VBox vbox = new VBox(textArea, button);
Scene scene = new Scene(vbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Setting the Text of a TextArea
You can set the text of a TextArea control via its setText() method. Here is an
example of setting the text of a TextArea control via setText() :
textArea.setText("New Text");
JavaFX Accordion
The JavaFX Accordion control is a container control which can contain several
sections internally, each of which can have their content expanded or collapsed.
The Accordion control is implemented by the JavaFX
class javafx.scene.control.Accordion. The section displayed inside it are made up
of JavaFX TitledPane controls. Here is a screenshot of a JavaFX Accordion control:
Notice that none of the sections are expanded. You can expand a section by
clicking on the little triangle next to the title for each section. Expanding a section
will reveal its content. Here is a screenshot of a JavaFX Accordion with a section
expanded:
JavaFX Accordion Example
Here is a full JavaFX Accordion example so you can quickly get an overview of what
its usage looks like:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class AccordionExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
Accordion accordion = new Accordion();
TitledPane pane1 = new TitledPane("Boats" , new Label("Show all boats
available"));
TitledPane pane2 = new TitledPane("Cars" , new Label("Show all cars
available"));
TitledPane pane3 = new TitledPane("Planes", new Label("Show all planes
available"));
accordion.getPanes().add(pane1);
accordion.getPanes().add(pane2);
accordion.getPanes().add(pane3);
VBox vBox = new VBox(accordion);
Scene scene = new Scene(vBox);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Create an Accordion
Before you can use the JavaFX Accordion control you must first instantiate it. You
instantiate it simply using the Java new command, like this:
Accordion accordion = new Accordion();
Add TitledPane Objects to Accordion
Each section displayed inside a JavaFX Accordion is represented by a JavaFX
TitledPane. To add sections to the Accordion control, you create on TitledPane per
section, and add it to the Accordion. Here is an example of
adding TitledPane sections to a JavaFX Accordion:
Accordion accordion = new Accordion();
TitledPane pane1 = new TitledPane("Boats" , new Label("Show all boats available"));
TitledPane pane2 = new TitledPane("Cars" , new Label("Show all cars available"));
TitledPane pane3 = new TitledPane("Planes", new Label("Show all planes
available"));
accordion.getPanes().add(pane1);
accordion.getPanes().add(pane2);
accordion.getPanes().add(pane3);
Add Accordion to Scene Graph
To make a JavaFX Accordion visible, you must add it to the scene graph. Here is
an example of adding a JavaFX Accordion to the JavaFX scene graph:
Accordion accordion = new Accordion();
VBox vBox = new VBox(accordion);
Scene scene = new Scene(vBox);
primaryStage.setScene(scene);
primaryStage.show();
Text Controls
1. ScrollPane
2. BorderPane
3. StackPane
4. GridPane
5. FlowPane
6. HBox and VBox
JavaFX ScrollPane
The JavaFX ScrollPane control is a container that has two scrollbars around the
component it contains if the component is larger than the visible area of the
ScrollPane. The scrollbars enable the user to scroll around the component shown
inside the ScrollPane, so different parts of the component can be seen. The
JavaFX ScrollPane controls is represented by the JavaFX
class javafx.scene.control.ScrollPane. Here is a screenshot of a
JavaFX ScrollPane with a JavaFX ImageView inside:
Create a ScrollPane
To use a JavaFX ScrollPane you must first create a ScrollPane instance. Here is an
example of creating a JavaFX ScrollPane instance:
ScrollPane scrollPane = new ScrollPane();
Set ScrollPane Content
Once you have created a JavaFX ScrollPane instance you can set the content you
want it to display via its setContent() method. Here is an example that sets a
JavaFX ImageView as content of a JavaFX ScrollPane:
ScrollPane scrollPane = new ScrollPane();
String imagePath = "images/aerial-beverage-caffeine-972533.jpg";
ImageView imageView = new ImageView(new Image(new FileInputStream(imagePath)));
scrollPane.setContent(imageView);
ScrollPane Viewport
The visible part of a JavaFX ScrollPane is called the ScrollPane viewport. As you
scroll around the content displayed inside the ScrollPane using the scrollbars, the
viewport is moved around the content too, making different parts of the content
visible.
Content With Effects or Transforms
If the content (JavaFX control) you want to display inside the
JavaFX ScrollPane uses effects or transforms, you must first wrap these controls in
a JavaFX Group. Otherwise the content won't be displayed correctly.
Pannable ScrollPane
By default the user can only navigate around the content displayed in a
JavaFX ScrollPane using its scrollbars. However, it is possible to make a
JavaFX ScrollPane pannable. A pannable ScrollPane enables the user to navigate its
content by holding down the left mouse button and move the mouse around. This
will have the same effect as using the scrollbars. However, using panning you can
move the content along both X and Y axis simultaneously. This is not possible
using the scrollbars, where the user can only operate one scrollbar at a time.
To switch a JavaFX ScrollPane into pannable mode you must set
its pannableProperty to the value true. Here is an example of switching a
JavaFX ScrollPane into pannable mode:
scrollPane.pannableProperty().set(true);
Fit To Width
The JavaFX ScrollPane fitToWidth property can make the ScrollPane fit its content to
the width of the ScrollPane viewport. To do so, the fitToWidth property must be set
to the value true. This property is ignored if the content node is not resizable. Here
is an example of setting the JavaFX ScrollPane fitToWidth property to true:
scrollPane.fitToWidthProperty().set(true);
Fit To Height
The JavaFX ScrollPane fitToHeight property can make the ScrollPane fit its content
to the height of the ScrollPane viewport. To do so, the fitToHeight property must be
set to the value true. This property is ignored if the content node is not resizable.
Here is an example of setting the JavaFX ScrollPane fitToHeight property to true:
scrollPane.fitToHeightProperty().set(true);
Showing and Hiding Scrollbars via ScrollBar Policies
It is possible to specify when the JavaFX ScrollPane is to show the vertical and
horizontal scrollbars. You do so via
the ScrollPane hbarPolicyProperty and vbarPolicyProperty properties. These
properties can be set to one of the ScrollPane.ScrollBarPolicy enum values. You
can choose from the values ALWAYS, AS_NEEDED and NEVER. Here is an example of
setting the hbarPolicyProperty and vbarPolicyProperty to ScrollBarPolicy.NEVER:
scrollPane.hbarPolicyProperty().setValue(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.vbarPolicyProperty().setValue(ScrollPane.ScrollBarPolicy.NEVER);
The above example removes the vertical and horizonal scrollbar from
the ScrollPane. Without the scrollbars the user cannot use them to scroll around the
content of the ScrollPane. However, if the ScrollPane is in pannable mode (see
earlier sections in this JavaFX ScrollPane tutorial) the user can still grab the
content and scroll around it with the mouse.
JavaFX TitledPane
The JavaFX TitledPane control is a container control which displays its content
inside a a pane (box) which at the top contains a title - hence the name TitledPane.
The TitledPane control is implemented by the javafx.scene.control.TitledPane class.
In this JavaFX TitledPane tutorial we will look at how to use the TitledPane control.
Here is a JavaFX TitledPane screenshot showing how it looks:
A TitledPane can be collapsed so only the title bar is visible. This functionality is
used inside the JavaFX Accordion control. The TitledPane can of course be
expanded too. I will show how that works later in this tutorial.
Creating a JavaFX TitledPane
In order to use a JavaFX TitledPane you must first create a TitledPane instance.
Here is an example of creating a JavaFX TitledPane:
Label label = new Label("The content inside the TitledPane");
TitledPane titledPane = new TitledPane("The Title", label);
Notice the second line in the code example. This is the line that creates
the TitledPane instance. Notice how the title to display in the TitledPane is passed as
a parameter to the constructor. Notice also, how the content to display, a JavaFX
Node, is also passed as a parameter to the constructor. In this example the content
is just a simple JavaFX Label.
Adding the TitledPane to the JavaFX Scene Graph
To make a JavaFX TitledPane instance visible, it must be added to a JavaFX scene
graph. Here is a full example of adding a JavaFX TitledPane to a JavaFX scene
graph:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TitledPaneExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Label label = new Label("The content inside the TitledPane");
TitledPane titledPane = new TitledPane("The Title", label);
Scene scene = new Scene(new VBox(titledPane));
primaryStage.setScene(scene);
primaryStage.show();
}
}
Collapse and Expand a TitledPane
The user can collapse and expand a JavaFX TitledPane using the small triangle
next to the title in the title bar of the TitledPane . Here is an example of how a
collapsed TitledPane looks:
Notice how the content of the TitledPane is no longer visible.
It is also possible to collapse and expand a TitledPane programmatically. You do so
by calling its setExpanded() method. Here is an example of expanding and collapsing
a TitledPane programmatically:
titledPane.setExpanded(true);
titledPane.setExpanded(false);
Disable Collapse
It is possible to disable the collapse functionality of a JavaFX TitledPane. You do so
by calling its setCollapsible() method, passing a value of false as parameter. Here
is how switching off the collapsible functionality of a TitledPane looks:
Label label = new Label("The content inside the TitledPane");
TitledPane titledPane = new TitledPane("The Title", label);
titledPane.setCollapsible(false);
JavaFX Pane
The JavaFX Pane class is a layout container which can contain other JavaFX
components internally, and lay them out. Actually, the JavaFX Pane class does not
actually provide any layout algorithm. The Pane class simply displays the
components it contains at the locations the components themselves want to be
located. In other words, the Pane class uses the layoutX and layoutY specified by its
child components to determine where to display them.
The JavaFX Pane class, javafx.scene.layout.Pane, is a subclass of the JavaFX
Region class, so it inherits all of the Region class functionality. That includes
functionality like borders, padding, background settings etc.
Create a JavaFX Pane
You create a JavaFX Pane simply via its standard no-arg constructor. Here is an
example of creating a JavaFX Pane instance:
Pane pane = new Pane();
Add Items to a JavaFX Pane
You add items JavaFX Pane by obtaining its list of children via getChildren(), and
then add the items to that list. Here is an example of adding a JavaFX Label to a
JavaFX Pane:
Pane pane = new Pane();
pane.getChildren().add(new Label("Hello Pane"));
If you repeat the last line multiple times, you will add multiple Label instances to the
Pane. Just keep in mind, that unless you change the layoutX and / or layoutY
properties of the added Labels, all the Label instances will be displayed in the same
X and Y position - meaning on top of each other.
Adding a JavaFX Pane to the Scene Graph
Here is an example of adding a JavaFX Pane to the JavaFX scene graph - by
setting the Pane as the root node of a JavaFX Scene:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class PaneExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
Pane pane = new Pane();
pane.getChildren().add(new Label("Hello Pane"));
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
JavaFX FlowPane
A JavaFX FlowPane is a layout component which lays out its child components
either vertically or horizontally, and which can wrap the components onto the next
row or column if there is not enough space in one row. The JavaFX FlowPane
layout component is represented by the class javafx.scene.layout.FlowPane
Creating a FlowPane
You create a JavaFX FlowPane via its constructor. Here is a
JavaFX FlowPane instantiation example:
FlowPane flowpane = new FlowPane();
Adding Children to a FlowPane
You can add children to a FlowPane by obtaining its child collection and add adding
the components to it you want the FlowPane to layout. Here is an example of adding
3 buttons to a FlowPane:
Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button Number 2");
Button button3 = new Button("Button Number 3");
FlowPane flowpane = new FlowPane();
flowpane.getChildren().add(button1);
flowpane.getChildren().add(button2);
flowpane.getChildren().add(button3);
Adding a FlowPane to the Scene Graph
To make a FlowPane visible you must add it to the JavaFX scene graph. To do so
you must add the FlowPane instance to a Scene object, or add the FlowPane to a layout
component which is added to a Scene object.
Here is an example of adding a JavaFX FlowPane to the scene graph:
package com.jenkov.javafx.layouts;
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class FlowPaneExperiments 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 Number 2");
Button button3 = new Button("Button Number 3");
FlowPane flowpane = new FlowPane();
flowpane.getChildren().add(button1);
flowpane.getChildren().add(button2);
flowpane.getChildren().add(button3);
Scene scene = new Scene(flowpane, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from this application looks like the following screen shots.
Notice how the buttons flow down onto the next horizontal line when the window
becomes too small to show them all in a single horizontal row.
Horizontal and Vertical Spacing
You can set the horizontal and vertical spacing between the components shown
inside a JavaFX FlowPane using its setHGap() and setVGap() methods. Here is an
example that shows how to set the horizontal and vertical gap between
components in a FlowPane :
flowpane.setHgap(10);
flowpane.setVgap(10);
When added to the example earlier, the resulting application would look like this:
Notice the horizontal and vertical gaps between the buttons now.
Orientation
By default the components in a FlowPane are layed out horizontally, wrapping onto
the next horizontal line when there is no longer space enough inside the FlowPane to
show more components horizontally.
You can change the flow orientation (direction) of a FlowPane using
its setOrientation() method. You can force the components to be layed out in
columns from top to bottom, and then change column when there is no more space
in the height to show more components. Here is how you do that:
flowpane.setOrientation(Orientation.VERTICAL);
JavaFX GridPane
A JavaFX GridPane is a layout component which lays out its child components in a
grid. The size of the cells in the grid depends on the components displayed in the
GridPane, but there are some rules. All cells in the same row will have the same
height, and all cells in the same column will have the same width. Different rows
can have different heights and different columns can have different widths.
The JavaFX GridPane is different from the TilePane in that a GridPane allows
different size of cells, whereas a TilePane makes all tiles the same size.
The number of rows and columns in a GridPane depends on the components added
to it. When you add a component to a GridPane you tell in what cell (row, column)
the component should be inserted, and how many rows and columns the
component should span.
The JavaFX GridPane layout component is represented by the
class javafx.scene.layout.GridPane
Creating a GridPane
You create a JavaFX GridPane via its constructor. Here is a
JavaFX GridPane instantiation example:
GridPane gridPane = new GridPane();
Adding Children to a GridPane
You can add children to a JavaFX GridPane in several ways. The easiest way is to
use the add() of the GridPane. Here is an example of adding 6 buttons to a GridPane:
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");
Button button4 = new Button("Button 4");
Button button5 = new Button("Button 5");
Button button6 = new Button("Button 6");
GridPane gridPane = new GridPane();
gridPane.add(button1, 0, 0, 1, 1);
gridPane.add(button2, 1, 0, 1, 1);
gridPane.add(button3, 2, 0, 1, 1);
gridPane.add(button4, 0, 1, 1, 1);
gridPane.add(button5, 1, 1, 1, 1);
gridPane.add(button6, 2, 1, 1, 1);
The first parameter of the add() method is the component (node) to add to
the GridPane.
The second and third parameter of the add() method is the column index and row
index of the cell in which the component should be displayed. Column and row
indexes start from 0.
The fourth and fifth parameter of the add() method are the oclumn span and row
span of the component, meaning how many rows and columns the component
should extend to. Column span and row span works similarly
to colspan and rowspan in an HTML table.
Adding a GridPane to the Scene Graph
To make a JavaFX GridPane visible you must add it to the JavaFX scene graph. To
do so you must add the GridPane instance to a Scene object, or add the GridPane to a
layout component which is added to a Scene object.
Here is an example of adding a JavaFX GridPane to the scene graph:
package com.jenkov.javafx.layouts;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class GridPaneExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("GridPane Experiment");
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");
Button button4 = new Button("Button 4");
Button button5 = new Button("Button 5");
Button button6 = new Button("Button 6");
GridPane gridPane = new GridPane();
gridPane.add(button1, 0, 0, 1, 1);
gridPane.add(button2, 1, 0, 1, 1);
gridPane.add(button3, 2, 0, 1, 1);
gridPane.add(button4, 0, 1, 1, 1);
gridPane.add(button5, 1, 1, 1, 1);
gridPane.add(button6, 2, 1, 1, 1);
Scene scene = new Scene(gridPane, 240, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The application resulting from this application looks like the following screen shots.
Spanning Multiple Rows and Columns
To see how to make a component span multiple columns and rows, look at this
modification of the 6 buttons added to the GridPane:
gridPane.add(button1, 0, 0, 2, 2);
gridPane.add(button2, 2, 0, 1, 1);
gridPane.add(button3, 2, 1, 1, 1);
gridPane.add(button4, 0, 2, 1, 1);
gridPane.add(button5, 1, 2, 1, 1);
gridPane.add(button6, 2, 2, 1, 1);
Notice how the first button added is given a column span and row span of 2. Notice
how the rest of the buttons are added outside of the top left 2 x 2 columns. The
layout resulting from these settings looks like this:
Horizontal and Vertical Spacing
You can set the horizontal and vertical spacing between the components shown
inside a JavaFX GridPane using its setHGap() and setVGap() methods. Here is an
example that shows how to set the horizontal and vertical gap between
components in a GridPane :
gridPane.setHgap(10);
gridPane.setVgap(10);
When added to the example earlier, the resulting application would look like this:
Notice the horizontal and vertical gaps between the buttons. If there were no gaps
set on the GridPane the buttons would have been positioned next to each other.
JavaFX HBox
The JavaFX HBox component is a layout component which positions all its child
nodes (components) in a horizontal row. The Java HBox component is represented
by the class javafx.scene.layout.HBox .
Create an HBox
You create an HBox using its constructor like this:
HBox hbox = new HBox();
HBox also has a constructor which takes a variable length list of components it
should layout. Here is an example of how to do that:
Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button Number 2");
HBox hbox = new HBox(button1, button2);
This HBox example will layout the two Button instances next to each other in a
horizontal row.
Adding an HBox to the Scene Graph
For an HBox to be visible it must be added to the scene graph. This means adding it
to a Scene object, or as child of a layout which is attached to a Scene object.
Here is an example that attaches a JavaFX HBox with the two Button instances to the
scene graph:
package com.jenkov.javafx.layouts;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class HBoxExperiments 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 Number 2");
HBox hbox = new HBox(button1, button2);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The result of running the above JavaFX HBox example is an application that looks
like this:
Notice that the two Button controls are kept on the same horizontal row even if there
is not enough space to show them in their fully preferred widths. The buttons do not
"wrap" down on the next line.
Child Node Spacing
In the earlier example the HBox positioned the nodes (button controls) right next to
each other. You can make the HBox insert some space between its nested controls
by providing the space in the HBox constructor. Here is an example of setting the
space between nested controls in an HBox:
HBox hbox = new HBox(20, button1, button2);
This example sets the spacing between the controls in the HBox layout component
to 20.
You can also set the space between the nested controls using
the setSpacing() meethod, like this:
hbox.setSpacing(50);
This example will set the spacing between nested controls to 50.
Child Node Margin
You can set the margin for child nodes of a JavaFX HBox using the
static setMargin() method. Here is an example of setting the margin around
a JavaFX Button using the setMargin() method:
Button button1 = new Button("Button 1");
HBox hbox = new HBox(button1);
HBox.setMargin(button1, new Insets(10, 10, 10, 10));
This example sets the margin around the Button inside the HBox to 10 on each
side.
Child Node Alignment
Since the JavaFX HBox is a container component, meaning it contains other
JavaFX components, you can specify how the HBox is to align the components it
contains. You do so via the HBox setAlignment() method. Here is an example of
setting the alignment of child nodes for a JavaFX HBox:
hbox.setAlignment(Pos.BASELINE_CENTER);
This example will make the HBox position its child nodes along the baseline
(vertically) of the vertical line, and from the center of the line and out (horizontally).
The JavaFX VBox control supports the following alignment options:
Parameter Vertically Horizontally
Pos.BASELINE_LEFT Baseline Left
Pos.BASELINE_CENTER Baseline Center
Pos.BASELINE_RIGHT Baseline Right
Pos.BOTTOM_LEFT Bottom Left
Pos.BOTTOM_CENTER Bottom Center
Pos.BOTTOM_RIGHT Bottom Right
Pos.CENTER_LEFT Center Left
Pos.CENTER Center Center
Pos.CENTER_RIGHT Center Right
Pos.TOP_LEFT Top Left
Pos.TOP_CENTER Top Center
Pos.TOP_RIGHT Top Right
Child Node hgrow
You can specify whether a child node of an HBox should grow horizontally to fill
any available space available inside the HBox. You do so via the
HBox setHgrow() static method. You have to specify which child node the rule is set
for. You do so by passing the child node as parameter to setHgrow(). You also have
to pass the horizontal expansion policy as parameter to setHgrow(). Here is an
example of telling that a child Button to expand horizontally if space is available
inside the HBox:
Button button1 = new Button("Button 1");
HBox hbox = new HBox(button1);
HBox.setHgrow(button1, Priority.ALWAYS);
The Priority class contains the following constants you can use to set the expansion
policy:
1. Policy.ALWAYS
2. Policy.SOMETIMES
3. Policy.NEVER
Please keep in mind that the HBox will only have extra horizontal space available if
the HBox is wider than the sum of the preferred widths of its children.
HBox Preferred Height
The default preferred height of an HBox is set to the same value as the largest
preferred height of any of its child nodes.
fillHeight
The JavaFX HBox fillHeight property can be used to tell the HBox control whether
it should expand the height of its children to fill out the whole height of the HBox, or
keep its children at their preferred heights.
The fillHeight property only affects child components which heights can actually
change. For instance, a Button does not change its height by default. It's max
height is set to its preferred height. However, you can override that by setting the
max height of the Button, or any other component you want to nest inside the
HBox, to a value different than its preferred value.
Here is an example showing how the fillHeight property works:
Button button1 = new Button("Button 1");
button1.setMaxHeight(99999.0D); //or Double.MAX_VALUE;
HBox hbox = new HBox(button1);
hbox.setFillHeight(true);
JavaFX VBox
The JavaFX VBox component is a layout component which positions all its child
nodes (components) in a vertical column - on top of each other. The JavaFX VBox
component is represented by the class javafx.scene.layout.VBox . In this JavaFX
VBox tutorial I will take a deeper look at the various options the VBox component
has for the layout of controls.
Create a VBox
To use the JavaFX VBox component you must first create an instance of the VBox
class. You create a VBox instance using its constructor like this:
VBox vbox = new VBox();
VBox also has a constructor which takes a variable length list of components it
should layout. Here is an example of how to do that:
Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button Number 2");
VBox vbox = new VBox(button1, button2);
This VBox example will layout the two Button instances one on top of the other in a
vertical column.
Adding a VBox to the Scene Graph
For a VBox instance to be visible it must be added to the scene graph. This means
adding it to a Scene object, or as child of another layout component which is
attached to a Scene object.
Here is an example that attaches a JavaFX VBox with the two Button instances to the
scene graph:
package com.jenkov.javafx.layouts;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class VBoxExperiments extends Application{
@Override
public void start(Stage primaryStage)
throws Exception {
primaryStage.setTitle("VBox Experiment 1");
Button button1 = new Button("Button Number 1");
Button button2 = new Button("Button Number 2");
VBox vbox = new VBox(button1, button2);
Scene scene = new Scene(vbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
The result of running the above JavaFX VBox example is an application that looks
like this:
Child Node Spacing
In the earlier example the VBox positioned the nodes (button controls) right under
the other. You can make the VBox insert some space between its nested controls by
providing the space in the VBox constructor. Here is an example of setting the space
between nested controls in an VBox:
VBox vbox = new VBox(20, button1, button2);
This example sets the spacing between the controls in the VBox layout component
to 20.
You can also set the space between the nested controls using
the setSpacing() method, like this:
vbox.setSpacing(50);
This example will set the spacing between nested controls to 50.
Child Node Alignment
Since the JavaFX VBox is a container component, meaning it contains other
JavaFX components, you can specify how the VBox is to align the components it
contains. You do so via the VBox setAlignment() method. Here is an example of
setting the alignment of child nodes for a JavaFX VBox:
vbox.setAlignment(Pos.BASELINE_CENTER);
This example will make the VBox position its child nodes along the baseline
(vertically) of the vertical line, and from the center of the line and out (horizontally).
The JavaFX VBox control supports the following alignment options:
Parameter Vertically Horizontally
Pos.BASELINE_LEFT Baseline Left
Pos.BASELINE_CENTER Baseline Center
Pos.BASELINE_RIGHT Baseline Right
Pos.BOTTOM_LEFT Bottom Left
Pos.BOTTOM_CENTER Bottom Center
Pos.BOTTOM_RIGHT Bottom Right
Pos.CENTER_LEFT Center Left
Pos.CENTER Center Center
Pos.CENTER_RIGHT Center Right
Pos.TOP_LEFT Top Left
Pos.TOP_CENTER Top Center
Pos.TOP_RIGHT Top Right
Center Horizontally
You can use the child node alignment features to horizontally center the child
nodes of a VBox. Here is an example showing how to center the child nodes of a
VBox horizontally:
vbox.setAlignment(Pos.BASELINE_CENTER);
Child Node Margin
You can set the margin for child nodes of a JavaFX VBox using the
static setMargin() method. Here is an example of setting the margin around
a JavaFX Button using the setMargin() method:
Button button = new Button("Button 1");
VBox vbox = new VBox(button);
VBox.setMargin(button, new Insets(10, 10, 10, 10));
This example sets the margin around the Button inside the VBox to 10 on each
side.
Child Node vgrow
You can specify whether a child node of a VBox should grow vertically to fill any
available space available inside the VBox. You do so via the VBox setVgrow() static
method. You have to specify which child node the rule is set for. You do so by
passing the child node as parameter to setVgrow(). You also have to pass the
vertical expansion policy as parameter to setVgrow(). Here is an example of telling
that a child Button to expand vertically if space is available inside the VBox:
Button button = new Button("Button 1");
VBox vbox = new VBox(button);
VBox.setVgrow(button, Priority.ALWAYS);
The Priority class contains the following constants you can use to set the expansion
policy:
1. Policy.ALWAYS
2. Policy.SOMETIMES
3. Policy.NEVER
Please keep in mind that the VBox will only have extra vertical space available if
the child nodes do not have the same preferred height, or if you explicitly set a
preferred height on the VBox that is larger than the preferred height of its child
nodes.
fillWidth
The JavaFX VBox fillWidth property can be used to tell the VBox control whether it
should expand the width of its children to fill out the whole width of the VBox, or
keep its children at their preferred widths.
The fillWidth property only affects child components which widths can actually
change. For instance, a Button does not change its width by default. It's max width
is set to its preferred width. However, you can override that by setting the max
width of the Button, or any other component you want to nest inside the VBox, to a
value different than its preferred value.
Here is an example showing how the fillWidth property works:
Button button = new Button("Button 1");
button.setMaxWidth(99999D); //or Double.MAX_VALUE;
VBox vbox = new VBox(button);
vbox.setFillWidth(true);
VBox CSS
Like many other JavaFX controls the VBox component can be styled via CSS. You
set the CSS styles of the JavaFX VBox component via its setStyle() method.
Styling JavaFX controls via CSS is covered in more detail in the JavaFX CSS
Styling tutorial, but I will briefly explain how to style a JavaFX VBox here. Here is
an example of setting the CSS styles of a JavaFX VBox component:
vbox.setStyle("-fx-padding: 16;");
The VBox component supports the following CSS properties:
CSS
Property
Description
-fx-padding
Sets the padding between the edge of the VBox and the edge of
the outermost child nodes.
-fx-border-
style
Sets the border style of the VBox, in case you want a visible
border around it.
-fx-border-
width
Sets the border width.
-fx-border- Sets the border insets.
insets
-fx-border-
radius
Sets the border radius (of corners).
-fx-border-
color
Sets the border color.
VBox FXML
You can define a JavaFX VBox from inside a JavaFX FXML document. Here is an
example of how a VBox FXML definition looks:
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<GridPane xmlns:fx="http://javafx.com/fxml"
fx:controller="sample.Controller"
alignment="center" hgap="10" vgap="10">
<VBox>
<Label>Text inside VBox</Label>
</VBox>
</GridPane>
Here are some of the most commonly used VBox XML element attributes:
• border
• alignment
• fillWidth
MENUS
MENU CONTROLS
1. Menu Basics
2. Menu bars
3. MenuItem
MENUBAR
JavaFX MenuBar
The JavaFX MenuBar provides JavaFX applications with a visual drop down menu
similar to that most desktop applications have at the top of their application window.
The JavaFX MenuBar is represented by the class javafx.scene.control.MenuBar . Here
is an example screenshot of what a JavaFX MenuBar can look like:
Creating a MenuBar Instance
Before you can use the JavaFX MenuBar you must create a MenuBar instance. Here is
an example of creating a JavaFX MenuBar instance:
MenuBar menuBar = new MenuBar();
Adding a MenuBar to the Scene Graph
Before a MenuBar becomes visible you will have to add it to the JavaFX scene graph.
Here is an example of adding a JavaFX MenuBar to the scene graph:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class JavaFXApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX App");
MenuBar menuBar = new MenuBar();
VBox vBox = new VBox(menuBar);
Scene scene = new Scene(vBox, 960, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Notice how the MenuBar is added to the root layout (VBox) of the JavaFX scene. This
places the MenuBar at the top of the application window.
Note that the above example does not add any menus or menu items to
the MenuBar, so if you run the example you will not actually see the MenuBar. We will
see how to add menus and menu items in the following sections.
Creating Menu Instances
Once the MenuBar instance is created, you can add Menu instances to it
(javafx.scene.control.Menu . A Menu instance represents a single vertical menu with
nested menu items. Thus, you can add multiple MenuBar instances to a MenuBar to
add multiple vertical drop down menus.
Here is an example of adding a Menu to a MenuBar :
Menu menu1 = new Menu("Menu 1");
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu1);
Here is a screenshot showing the JavaFX MenuBar as configured by the example
code above:
As you can see, there is only a single menu in the MenuBar titled "Menu 1" . This
menu has no menu items nested under it. We will see how to add menu items to
a Menu in the following sections.
Menu Graphics
You can set a graphic icon for a Menu by calling its setGraphic() method. The graphic
icon will be displayed next to the text label of the menu. Here is an example of
setting a graphic icon for a JavaFX Menu instance:
Menu menu = new Menu("Menu 1");
menu.setGraphic(new ImageView("file:volleyball.png"));
Here is how the resulting menu could look in a JavaFX application:
Menu Events
A JavaFX Menu instance can fire several events which you can listen for in your
application. The most commonly used events are:
• onShowing
• onShown
• onHiding
• onHidden
When a Menu is clicked with the mouse it shows its contents. This action fires the
event onShowing before the Menu starts showing its menu items. Once the menu is
fully visible the onShown event is fired.
When an shown (open) Menu is clicked with the mouse it hides its contents again.
This action fires the event onHiding before the Menu starts hiding its menu items.
Once the menu is fully hidden the onHidden event is fired.
You can set Menu event listeners for the events above using the
methods setOnShowing(), setOnShown(), setOnHiding() and setOnHidden(). Here is an
example of setting event listeners for these events on a JavaFX Menu :
Menu menu = new Menu("Menu 1");
menu.setOnShowing(e -> { System.out.println("Showing Menu 1"); });
menu.setOnShown (e -> { System.out.println("Shown Menu 1"); });
menu.setOnHiding (e -> { System.out.println("Hiding Menu 1"); });
menu.setOnHidden (e -> { System.out.println("Hidden Menu 1"); });
The Menu event listeners set above only print out a message to the console when
the events fired. You could do something more advanced in case you needed to.
Adding Menu Items
Once you have created a Menu instance you must add one or
more MenuItem instances to it. Each MenuItem corresponds to a menu item in the
menu it is added to. Here is an example of adding 2 MenuItem instances to a Menu,
which is then added to a MenuBar:
Menu menu = new Menu("Menu 1");
MenuItem menuItem1 = new MenuItem("Item 1");
MenuItem menuItem2 = new MenuItem("Item 2");
menu.getItems().add(menuItem1);
menu.getItems().add(menuItem2);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu);
Here is what the resulting JavaFX MenuBar would look like, if used in a JavaFX
application:
MenuItem Graphics
You can add an icon to a menu item. You add a graphic icon to a MenuItem by
calling its setGraphic() method, passing as parameter the graphic you want to use
for the given MenuItem. Here is an example that adds images to the menu items
created in the example in the previous section:
Menu menu = new Menu("Menu 1");
MenuItem menuItem1 = new MenuItem("Item 1");
menuItem1.setGraphic(new ImageView("file:soccer.png"));
MenuItem menuItem2 = new MenuItem("Item 2");
menuItem1.setGraphic(new ImageView("file:basketball.png"));
menu.getItems().add(menuItem1);
menu.getItems().add(menuItem2);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu);
Here is how a JavaFX MenuBar looks with graphic icons added to its menu items:
MenuItem Events
The MenuBar configurations created in the previous examples do not react if you
select any of the menu items. In order to respond to the selection of a MenuItem you
must set an event listener on the MenuItem. Here is an example of adding an event
listener to a JavaFX MenuItem:
MenuItem menuItem1 = new MenuItem("Item 1");
menuItem1.setOnAction(e -> {
System.out.println("Menu Item 1 Selected");
});
Notice the Java Lambda added as parameter to the setOnAction() method of
the MenuItem . This lambda expression is executed when the menu item is selected.
Submenus
The JavaFX MenuBar supports multiple layers of menus. A menu nested inside
another menu is called a submenu. The Menu class extends the MenuItem class and
can therefore be used as a menu item inside another Menu instance. Here is an
example that creates a single JavaFX menu with a submenu inside:
Menu menu = new Menu("Menu 1");
Menu subMenu = new Menu("Menu 1.1");
MenuItem menuItem11 = new MenuItem("Item 1.1.1");
subMenu.getItems().add(menuItem11);
menu.getItems().add(subMenu);
MenuItem menuItem1 = new MenuItem("Item 1");
menu.getItems().add(menuItem1);
MenuItem menuItem2 = new MenuItem("Item 2");
menu.getItems().add(menuItem2);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu);
The JavaFX MenuBar resulting from the above example will look similar to this:
Check Menu Items
The JavaFX MenuBar supports using check menu items in a menu. A check menu
item is a menu item that can be "selected" and remain selected until unselected
later. A small check mark is displayed next to the check menu item as long as it
remains selected.
The check menu item is represented by
the CheckMenuItem (javafx.scene.control.CheckMenuItem) class. Here is an example of
a JavaFX menu with a CheckMenuItem in:
CheckMenuItem checkMenuItem = new CheckMenuItem("Check this!");
menu.getItems().add(checkMenuItem);
The Menu instance then need to be added to a MenuBar to be visible, as you have
seen in earlier examples. Here is how the resulting menu looks, with the check
menu menu item checked:
Radio Menu Item
The JavaFX MenuBar also supports radio menu items. Radio menu items are menu
items of which only one of a set of menu items can be selected - just like
standard JavaFX radio buttons.
The radio menu item is represented by the RadioMenuItem.
The RadioMenuItem instance must be added to a ToggleGroup to make them mutually
exclusive. That is how JavaFX knows which RadioMenuItem instance belong together.
Here is an example of a JavaFx menu that uses a set of radio menu items:
Menu menu = new Menu("Menu 1");
RadioMenuItem choice1Item = new RadioMenuItem("Choice 1");
RadioMenuItem choice2Item = new RadioMenuItem("Choice 2");
RadioMenuItem choice3Item = new RadioMenuItem("Choice 3");
ToggleGroup toggleGroup = new ToggleGroup();
toggleGroup.getToggles().add(choice1Item);
toggleGroup.getToggles().add(choice2Item);
toggleGroup.getToggles().add(choice3Item);
menu.getItems().add(choice1Item);
menu.getItems().add(choice2Item);
menu.getItems().add(choice3Item);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu);
Here is how the JavaFx menu resulting from this example code looks:
Menu Item Separators
The MenuBar supports menu item separators. A separator is a horizontal line that
separates groups of menu items. A separator is often used to signal to users what
menu items are related to each other.
Menu item separators are represented by the SeparatorMenuItem class. Here is an
example of a menu with two menu items separated by a SeparatorMenu:
MenuItem item1 = new MenuItem("Item 1");
MenuItem item2 = new MenuItem("Item 2");
SeparatorMenuItem separator = new SeparatorMenuItem();
menu.getItems().add(item1);
menu.getItems().add(separator);
menu.getItems().add(item2);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu);
Here is how the resulting JavaFX menu would look like:
Custom Control Menu Items
The JavaFX MenuBar also supports using custom JavaFX controls as menu items.
To do so you need to use the CustomMenuItem (javafx.scene.control.CustomMenuItem)
class.
The CustomMenuItem class has a setContent() method which you can use to set the
custom JavaFX control to show in the menu. Here is an example that shows both
a JavaFX Button and a JavaFX Slider as custom menu items:
Menu menu = new Menu("Menu 1");
Slider slider = new Slider(0, 100, 50);
CustomMenuItem customMenuItem = new CustomMenuItem();
customMenuItem.setContent(slider);
customMenuItem.setHideOnClick(false);
menu.getItems().add(customMenuItem);
Button button = new Button("Custom Menu Item Button");
CustomMenuItem customMenuItem2 = new CustomMenuItem();
customMenuItem2.setContent(button);
customMenuItem2.setHideOnClick(false);
menu.getItems().add(customMenuItem2);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu);
Notice the call to CustomMenuItem setHideOnClick() with the value false as parameter.
This is done to keep the menu open while the user interacts with the custom menu
item control. If you set the value to true the menu will close as soon as the user
clicks the control the first time, making further interaction impossible. For normal
menu items you actually do want the menu to close immediately, but for some
custom menu items you may not want that. The menu can still be closed by clicking
on the menu title again.
Here is how the resulting menu looks:
JavaFX ContexMenu
The JavaFX ContextMenu component provides a standard right click menu for
JavaFX controls. The JavaFX ContextMenu is represented by the
class javafx.scene.control.ContextMenu. You create a ContextMenu instance and
attach it to the JavaFX control you want the ContextMenu to be active for. Here is a
screenshot of a JavaFX TextArea with a ContextMenu attached and shown:
Full ContextMenu Example
Here is a full JavaFX ContextMenu example to give you a quick overview of how
using the ContextMenu looks:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ContextMenuExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
ContextMenu contextMenu = new ContextMenu();
MenuItem menuItem1 = new MenuItem("Choice 1");
MenuItem menuItem2 = new MenuItem("Choice 2");
MenuItem menuItem3 = new MenuItem("Choice 3");
menuItem3.setOnAction((event) -> {
System.out.println("Choice 3 clicked!");
});
contextMenu.getItems().addAll(menuItem1,menuItem2,menuItem3);
TextArea textArea = new TextArea();
textArea.setContextMenu(contextMenu);
VBox vBox = new VBox(textArea);
Scene scene = new Scene(vBox);
primaryStage.setScene(scene);
primaryStage.setTitle("JavaFX App");
primaryStage.show();
}
}
Create a ContextMenu
To use a JavaFX ContextMenu you must first create a ContextMenu instance. Here is
an example of creating a JavaFX ContextMenu:
ContextMenu contextMenu = new ContextMenu();
Add Menu Items to the ContextMenu
The ContextMenu needs one or more MenuItem instances which are displayed in the
menu. To detect which menu item was clicked, you add listeners to
the MenuItem instances. Here is an example of adding MenuItem instances to
a ContextMenu:
ContextMenu contextMenu = new ContextMenu();
MenuItem menuItem1 = new MenuItem("Choice 1");
MenuItem menuItem2 = new MenuItem("Choice 2");
MenuItem menuItem3 = new MenuItem("Choice 3");
menuItem3.setOnAction((event) -> {
System.out.println("Choice 3 clicked!");
});
contextMenu.getItems().addAll(menuItem1,menuItem2,menuItem3);
Notice how there is an onAction listener set on the third MenuItem,
using setOnAction(), passing Java Lambda Expression as listener. If
this MenuItem is clicked, the action listener is executed.
Add ContextMenu to JavaFX Control
A JavaFX ContextMenu needs to be attached to a JavaFX control to be active. You
add a ContextMenu to a control via the setContextMenu() of a JavaFX control. Here is
an example of adding a JavaFX ContextMenu to a JavaFX control:
TextArea textArea = new TextArea();
textArea.setContextMenu(contextMenu);
MENU CONTROLS
4. Menus
5. Basics
6. Menu
7. Menu bars
8. MenuItem
JAVAFX ADDITIONAL FEATURES
Charts
• JavaFX comes with a set of built-in ready-to-use chart components.
• It is not have to code charts from scratch every time you need a basic chart.
JavaFX contains the following chart components:
• AreaChart
• BarChart
• BubbleChart
• LineChart
• PieChart
• ScatterChart
• StackedAreaChart
• StackedBarChart
2D Graphics
JavaFX contains features that makes it easy to draw 2D graphics on the screen.
3D Graphics
• JavaFX contains features that make it easy to draw 3D graphics on the screen.
Audio
• JavaFX contains features that make it easy to play audio in JavaFX applications.
• This is typically useful in games or educational applications.
Video
JavaFX contains features that makes it easy to play video in JavaFX applications. This is
typically useful in streaming applications, games or educational applications.
WebView
• JavaFX contains a WebView component which is capable of showing web pages
(HTML5, CSS etc.).
• The JavaFX WebView component is based on WebKit - the web page rendering
engine also used in Chrome and Safari.
• The WebView component makes it possible to mix a desktop application with a
web application.
• There are times where that is useful.
• For instance, if you already have a decent web application, but need some features
which can only be provided sensibly with a desktop application - like disk access,
communication with other network protocols than HTTP (e.g UDP, IAP etc.) .

More Related Content

PDF
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
PDF
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
PDF
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
PDF
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
PPTX
Access modifiers in java
PPT
Exception handling
PPTX
Java exception handling
PPTX
Access Modifier.pptx
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
Access modifiers in java
Exception handling
Java exception handling
Access Modifier.pptx

What's hot (20)

PDF
Software Engineering :UML class diagrams
PPTX
Introduction to software testing
PPTX
Validation testing
PPT
Coupling and cohesion
PPTX
Function Point Analysis
PPT
Flow oriented modeling
PPTX
Waterfall model in SDLC
PPTX
Introduction to java
PPTX
software product and its characteristics
PPTX
OOPS In JAVA.pptx
PPTX
Software project estimation
PPTX
Waterfall Model PPT in Software Engineering
PPT
Risk management in software engineering
PPTX
Software Configuration Management
PPTX
Event handling
PPTX
Waterfall model ppt final
PPTX
Software Project Management - Staffing
PPTX
File Management and manipulation in C++ Programming
PPTX
Software quality
PPTX
Dag representation of basic blocks
Software Engineering :UML class diagrams
Introduction to software testing
Validation testing
Coupling and cohesion
Function Point Analysis
Flow oriented modeling
Waterfall model in SDLC
Introduction to java
software product and its characteristics
OOPS In JAVA.pptx
Software project estimation
Waterfall Model PPT in Software Engineering
Risk management in software engineering
Software Configuration Management
Event handling
Waterfall model ppt final
Software Project Management - Staffing
File Management and manipulation in C++ Programming
Software quality
Dag representation of basic blocks
Ad

Similar to CS3391 -OOP -UNIT – V NOTES FINAL.pdf (20)

PPTX
Java AWT and Java FX
PDF
Java FX Part2
PPTX
Untitled (1)-------------------------------------------------.pptx
PDF
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
PPTX
Advance Java Programming(CM5I) Event handling
PPTX
JAVA (UNIT 5)
PPTX
event-handling.pptx
PDF
Ajp notes-chapter-03
PPT
Events1
PPS
Dacj 2-2 b
PPT
engineeringdsgtnotesofunitfivesnists.ppt
PPTX
UNIT III Event Handling of the car j.pptx
PPTX
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
PPT
Unit 5.133333333333333333333333333333333.ppt
PPTX
Module3.11.pptx
PPTX
Module 5.pptx
PPT
GUI design using JAVAFX.ppt
PPTX
Advance java programming- Event handling
ODP
JavaFX in Action Part I
PPT
Unit 6 Java
Java AWT and Java FX
Java FX Part2
Untitled (1)-------------------------------------------------.pptx
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
Advance Java Programming(CM5I) Event handling
JAVA (UNIT 5)
event-handling.pptx
Ajp notes-chapter-03
Events1
Dacj 2-2 b
engineeringdsgtnotesofunitfivesnists.ppt
UNIT III Event Handling of the car j.pptx
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
Unit 5.133333333333333333333333333333333.ppt
Module3.11.pptx
Module 5.pptx
GUI design using JAVAFX.ppt
Advance java programming- Event handling
JavaFX in Action Part I
Unit 6 Java
Ad

More from AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING (20)

PPTX
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
PPTX
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
PPTX
CS3391 OOP UT-I T1 OVERVIEW OF OOP
PPTX
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
PPTX
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
PDF
CS8080 information retrieval techniques unit iii ppt in pdf
PDF
PDF
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
PDF
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
PDF
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
PDF
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
PDF
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
PDF
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
PDF
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
PDF
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
PDF
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
PDF
CS8080_IRT_UNIT - III T8 FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdf
PDF
CS8080_IRT_UNIT - III T7 SVM CLASSIFIER.pdf
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
CS3391 OOP UT-I T1 OVERVIEW OF OOP
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
CS8080 information retrieval techniques unit iii ppt in pdf
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
CS8080_IRT_UNIT - III T8 FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdf
CS8080_IRT_UNIT - III T7 SVM CLASSIFIER.pdf

Recently uploaded (20)

PPTX
Lecture Notes Electrical Wiring System Components
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPT
Project quality management in manufacturing
PPTX
Sustainable Sites - Green Building Construction
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
composite construction of structures.pdf
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
DOCX
573137875-Attendance-Management-System-original
PPTX
additive manufacturing of ss316l using mig welding
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
PPT on Performance Review to get promotions
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Lecture Notes Electrical Wiring System Components
OOP with Java - Java Introduction (Basics)
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Project quality management in manufacturing
Sustainable Sites - Green Building Construction
CYBER-CRIMES AND SECURITY A guide to understanding
composite construction of structures.pdf
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
573137875-Attendance-Management-System-original
additive manufacturing of ss316l using mig welding
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPT on Performance Review to get promotions
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Foundation to blockchain - A guide to Blockchain Tech
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...

CS3391 -OOP -UNIT – V NOTES FINAL.pdf

  • 1. DEPARTMENT OF INFORMATION TECHNOLOGY R2017 - SEMESTER III CS3391 – OBJECT ORIENTED PROGRAMMING UNIT V - JAVAFX EVENT HANDLING, CONTROLS AND COMPONENTS CLASS NOTES Complimented with PERSONALIZED LEARNING MATERIAL (PLM) With PERSONALIZED ASSESSMENT TESTS (PATs)
  • 2. ction to PERSONALIZED LEARNING MATERIAL (PLM) The PERSONALIZED LEARNING MATERIAL (PLM) is special Type of Learning Material designed and developed by Er. K.Khaja Mohideen , Assistant Professor , Aalim Muhammed Salegh College of Engineering, Avadi-IAF, Chennai – 600 055, India. This material called PLM is an innovative Learning Type based Artificial Intelligence based Suggestive learning Strategy (SLS) that recommends the selective Topics to Learners of different Learning mind sets groups. We identified three major such Learner Groups from Subject Learning Student Communities and are as follows: 1) Smart Learning Groups 2) Effective Learning Groups 3) Slow Learning Groups The three Coloring depicts the following levels of Experiencing Learners groups: 1) Smart Learning Groups – Greenish Shadow 2) Effective Learning Groups – Orange Shadow 3) Slow Learning Groups – Red Shadow The following picture illustrates the same: Note: The decision on PLM Topic grouping type is based on the Designer’s Academic Experience and his Academic Excellence on the selective Course Domain. MOST IMPORTANT IMPORTANT NOT IMPORTANT
  • 3. PLM with PAT - TASKS TO BE EXECUTED 1) SELECT YOUR TOPIC OF CHOICE ➢ You can choose the Topic of your Interest from the selected UNIT of the Selected Subject. 2) INTRODUCTION OF SUB-TOPICS ➢ Identify and list the Sub-topics for the above selected main topic from the selected UNIT of the Selected Subject. 3) KEYWORDS OF SELECTED TOPICS ➢ Continue to identify the Keywords or main key terms of the above selected main topic from the selected UNIT of the Selected Subject. 4) FORMING THE KEY STATEMENTS ➢ Form the answer statement(s) from the keyword and justify the answer framed. 5) TAKE THE PERSONALIZED ASSESSMENT TEST (PAT)
  • 4. PERSONALIZED ASSESSMENT TESTS (PATs) An Introduction to PAT Personalized Assessment Test(PAT) is a specialized Assessment meant for different Learners groups of Aalim Muhammed Salegh Salegh College of Engineering. The major test type includes: 1) Multiple Choice Question (MCQ) Test(s) 2) Fill in the blank Test(s) 3) Descriptive Question Type Test(s) NOTE: The mode of conduct of the PAT Assessment is based on the time and resource availability. That is it is either OFF-LINE or ON-LINE mode. Refer ANNEXTURE – A FOR PERSONALIZED ASSESSMENT TEST (PAT)
  • 5. INDEX SL No. Topic PAGE NO. UNIT – V : Syllabus with PL 05 1 JAVAFX Events and Controls: Event Basics 06 2 Handling Key and Mouse Events. 10 3 Controls: Checkbox, 12 4 ToggleButton 17 5 RadioButtons 27 6 ListView 32 7 ComboBox 55 8 ChoiceBox 60 9 Text Controls 65 10 ScrollPane. 67 Layouts – FlowPane – HBox and VBox – BorderPane – StackPane – GridPane. Menus – Basics – Menu – Menu bars – MenuItem. TAKE :- PERSONALIZED ASSESSMENT TEST (PAT) -I
  • 6. UNIT – V UNIT V: JAVAFX EVENT HANDLING, CONTROLS AND COMPONENTS 9 JAVAFX Events and Controls: Event Basics – Handling Key and Mouse Events. Controls: Checkbox, ToggleButton – RadioButtons – ListView – ComboBox – ChoiceBox – Text Controls – ScrollPane. Layouts – FlowPane – HBox and VBox – BorderPane – StackPane – GridPane. Menus – Basics – Menu – Menu bars – MenuItem. NOTE: ➔ Important Topic → Less Important ➔ → Not Important
  • 7. Graphics programming • Java contains support for graphics that enable programmers to visually enhance applications. • Java contains many more sophisticated drawing capabilities as part of the Java 2D API. Swing • Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java. • Unlike AWT, Java Swing provides platform-independent and lightweight components.
  • 8. • The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc. JAVAFX JAVAFX Events and Controls Events: Event Basics – Handling Key and Mouse Events. Controls: Checkbox, ToggleButton – RadioButtons – ListView – ComboBox – ChoiceBox – Text Controls Layouts – ScrollPane - FlowPane – HBox and VBox – BorderPane – StackPane – GridPane. Menus – Basics – Menu – Menu bars – MenuItem.
  • 9. JAVAFX PLATFORM FOR JAVA GUI APPLICATION DEVELOPMENT AN OVERVIEW OF JAVA GUI APPLICATION DEVELOPMENT
  • 10. INTRODUCTION TO JAVAFX • JavaFX is a software platform for creating and delivering desktop applications, as well as rich web applications that can run across a wide variety of devices • This course will get you started with the fundamentals of GUI development using JavaFX • Understanding the basics of JavaFX and visualizing the JavaFX structure • Getting started with JavaFX and creating your first ever GUI using Java. Learning how to add various elements such as Text, Links, and Buttons to the JavaFX GUI • Understanding Transactions, Scripting, and Connections in Redis • Exploring layouts in JavaFX. JavaFX is a software platform that will be imported from: import java.javafx.*; It has the following components: a) javafx.base b) javafx.controls c) javafx.fxml d) javafx.graphics e) javafx.media f) javafx.web Uses
  • 11. Students who wish to get hands-on an amazing GUI development framework - JavaFX Users who wish to learn GUI and desktop application development using Java Benefits • JavaFX is based on a scene graph model that is superior to models used by Java 2D and Swing • JavaFX performs well • JavaFX has properties and binding • You don’t have to abandon your Swing code to begin using JavaFX • JavaFX Scene Builder is a great tool for creating JavaFX UIs • JavaFX includes 3D. 1. Event Basics 1.1 Event handling in JAVA What are the components of event handling? • An event represents an occurrence of something of interest to the application, such as a mouse being moved or a key being pressed. Event handling has three main components a) Events: An event is a change in state of an object. b) Events Source: An event source is an object that generates an event. c) Listeners: A listener is an object that listens to the event. A listener gets notified when an event occurs. 1.2 Event Handling in JAVAFX How are events handled in JavaFX? • In JavaFX applications, events are notifications that something has happened. • As a user clicks a button, presses a key, moves a mouse, or performs other actions, events are dispatched.
  • 12. • Registered event filters and event handlers within the application receive the event and provide a response. • In JavaFX, an event is an instance of the javafx.event. • Event class or any subclass of Event. • JavaFX provides several events, including DragEvent, KeyEvent, MouseEvent, ScrollEvent, and others. • You can define your own event by extending the Event class. Event Properties Every event includes the information described in Table 1-1. Table 1-1 Event Properties Property Description Event type Type of event that occurred. Source Origin of the event, with respect to the location of the event in the event dispatch chain. The source changes as the event is passed along the chain. Target Node on which the action occurred and the end node in the event dispatch chain. The target does not change, however if an event filter consumes the event during the event capturing phase, the target will not receive the event. • Event subclasses provide additional information that is specific to the type of event. • For example, the MouseEvent class includes information such as which button was pushed, the number of times the button was pushed, and the position of the mouse.
  • 13. Package javafx.event Provides basic framework for FX events, their delivery and handling. See: Description • Interface Summary Interface Description EventDispatchChain Represents a chain of EventDispatcher objects, which can dispatch an Event. EventDispatcher An EventDispatcher represents an event dispatching and processing entity. EventHandler<T extends Event> Handler for events of a specific class / type. EventTarget Represents an event target. • Class Summary Class Description ActionEvent An Event representing some type of action. Event Base class for FX events. EventType<T extends Event> This class represents a specific event type associated with an Event. WeakEventHandler<T extends Event> Used in event handler registration in place of its associated event handler Event Types • An event type is an instance of the EventType class. • Event types further classify the events of a single event class. • For example, the KeyEvent class contains the following event types: • KEY_PRESSED • KEY_RELEASED • KEY_TYPED • Event types are hierarchical. Every event type has a name and a super type. For example, the name of the event for a key being pressed
  • 14. is KEY_PRESSED, and the super type is KeyEvent.ANY. The super type of the top-level event type is null. Figure 1-1 shows a subset of the hierarchy. Figure 1-1 Event Type Hierarchy Description of "Figure 1-1 Event Type Hierarchy" • The top-level event type in the hierarchy is Event.ROOT, which is equivalent to Event.ANY. • In the subtypes, the event type ANY is used to mean any event type in the event class. For example, to provide the same response to any type of key event, use KeyEvent.ANY as the event type for the event filter or event handler. • To respond only when a key is released, use the KeyEvent.KEY_RELEASED event type for the filter or handler. Event Targets • The target of an event can be an instance of any class that implements the EventTarget interface. • The implementation of the buildEventDispatchChain creates the event dispatch
  • 15. chain that the event must travel to reach the target. • The Window, Scene, and Node classes implement the EventTarget interface and subclasses of those classes inherit the implementation. • Therefore, most of the elements in your user interface have their dispatch chain defined, enabling you to focus on responding to the events and not be concerned with creating the event dispatch chain. • If you create a custom UI control that responds to user actions and that control is a subclass of Window, Scene, or Node, your control is an event target through inheritance. • If your control or an element of your control is not a subclass of Window, Scene, or Node, you must implement the EventTarget interface for that control or element. • For example, the MenuBar control is a target through inheritance, but the MenuItem element of a menu bar must implement the EventTarget interface so that it can receive events. Event Delivery Process The event delivery process contains the following steps: a) Target selection b) Route construction c) Event capturing d) Event bubbling a) Target Selection • When an action occurs, the system determines which node is the target based on internal rules: • For key events, the target is the node that has focus. • For mouse events, the target is the node at the location of the cursor. For synthesized mouse events, the touch point is considered the location of the cursor. • For continuous gesture events that are generated by a gesture on a touch screen, the target is the node at the center point of all touches at the beginning of the gesture. For indirect gesture events that are generated by a gesture on something other than a touch screen, such as a trackpad, the target is the node at the location of the cursor. • For swipe events that are generated by a swipe on a touch screen, the target is the node at the center of the entire path of all of the fingers. For indirect swipe events,
  • 16. the target is the node at the location of the cursor. • For touch events, the default target for each touch point is the node at the location first pressed. A different target can be specified using the ungrab(), grab(), or grab(node) methods for a touch point in an event filter or event handler. • If more than one node is located at the cursor or touch, the topmost node is considered the target. For example, if a user clicks or touches the triangle shown in Figure 1-2, the triangle is the target, not the rectangle that contains the circle and the triangle. Figure 1-2 Sample User Interface Event Targets Description of "Figure 1-2 Sample User Interface Event Targets" • When a mouse button is pressed and the target is selected, all subsequent mouse events are delivered to the same target until the button is released. • Similarly for gesture events, from the start of the gesture to the completion of the gesture, gesture events are delivered to the target identified at the beginning of the gesture. • The default for touch events is to deliver the events to the initial target node that was identified for each touch point, unless the target is modified using the ungrab(), grab(), or grab(node) methods. b) Route Construction • The initial event route is determined by the event dispatch chain that was created in the implementation of the buildEventDispatchChain() method of the selected event target. • For example, if a user clicks the triangle shown in Figure 1-2, the initial route is shown by the gray nodes in Figure 1-3. When a scene graph node is selected as an event target, the initial event route set in the default implementation of the buildEventDispatchChain() method in the Node class is a path from the stage to itself.
  • 17. Figure 1-3 Event Dispatch Chain Description of "Figure 1-3 Event Dispatch Chain" The route can be modified as event filters and event handlers along the route process the event. Also, if an event filter or event handler consumes the event at any point, some nodes on the initial route might not receive the event. c) Event Capturing Phase • In the event capturing phase, the event is dispatched by the root node of your application and passed down the event dispatch chain to the target node. Using the event dispatch chain shown in Figure 1-3, the event travels from the Stage node to the Triangle node during the event capturing phase. • If any node in the chain has an event filter registered for the type of event that occurred, that filter is called. When the filter completes, the event is passed to the next node down the chain. If a filter is not registered for a node, the event is passed to the next node down the chain. If no filter consumes the event, the event target eventually receives and processes the event. d) Event Bubbling Phase • After the event target is reached and all registered filters have processed the event, the event returns along the dispatch chain from the target to the root node. • Using the event dispatch chain shown in Figure 1-3, the event travels from the Triangle node to the Stage node during the event bubbling phase. • If any node in the chain has a handler registered for the type of event encountered,
  • 18. that handler is called. • When the handler completes, the event is returned to the next node up the chain. • If a handler is not registered for a node, the event is returned to the next node up the chain. If no handler consumes the event, the root node eventually receives the event and processing is completed. 1.3 Sample JavaFX Application package yourapplication; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; public class YourApplication extends Application { /** * @param args the command line arguments */ public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Hello World"); Group root = new Group(); Scene scene = new Scene(root, 300, 250); Button btn = new Button(); btn.setLayoutX(100); btn.setLayoutY(80); btn.setText("Hello World");
  • 19. btn.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { System.out.println("Hello World"); } }); root.getChildren().add(btn); primaryStage.setScene(scene); primaryStage.show(); } } The "Hello World" code creates a window with a single button. The setOnAction() method is used to register an event handler that handles the action events that are dispatched when the button is clicked. The handle() method in the event handler handles the event by printing the string "Hello World" to the console. 1.4 Keyboard Events The Keyboard example demonstrates the following uses of handlers: a) Registering a single handler for two different event types b) Providing common event processing for child nodes in a parent node Figure 4-1 is the screen that is shown when the Keyboard Example is started. • The user interface consists of four letters, each in its own square, which represent the corresponding keyboard key. • The first key on the screen is highlighted, which indicates that it has the focus. • Use the left and right arrow keys on the keyboard to move the focus to a different key on the screen. Figure 4-1 Initial Screen for Keyboard Example
  • 20. Description of Figure 4-1 follows Description of "Figure 4-1 Initial Screen for Keyboard Example" When the Enter key is pressed, the key on the screen with the focus changes to red. When the Enter key is released, the key on the screen returns to its previous color. When the key for a letter that matches one of the keys on the screen is pressed, the matching key on the screen changes to red, and returns to its previous color when the key is released. When a key that does not match any key on the screen is pressed, nothing happens. Figure 4-2 shows the screen when the A key has focus and the D key on the keyboard is pressed. Figure 4-2 Key Pressed Screen Description of Figure 4-2 follows Description of "Figure 4-2 Key Pressed Screen" Handlers for the Keyboard Example • In the Keyboard example, internally each key shown on the screen is represented by a key node. All key nodes are contained in a single keyboard node. • Each key node has a handler that receives key events when the key has focus. • The handler responds to the key-pressed and key-released events for the Enter key by changing the color of the key on the screen. • The event is then consumed so that the keyboard node, which is the parent node, does not receive the event.
  • 21. Example 4-3 shows the installEventHandler() method that defines the handler for the key nodes. Example 4-3 Handler for the Key Nodes private void installEventHandler(final Node keyNode) { // handler for enter key press / release events, other keys are // handled by the parent (keyboard) node handler final EventHandler<KeyEvent> keyEventHandler = new EventHandler<KeyEvent>() { public void handle(final KeyEvent keyEvent) { if (keyEvent.getCode() == KeyCode.ENTER) { setPressed(keyEvent.getEventType() == KeyEvent.KEY_PRESSED); keyEvent.consume(); } } }; keyNode.setOnKeyPressed(keyEventHandler); keyNode.setOnKeyReleased(keyEventHandler); } • The keyboard node has two handlers that handle key events that are not consumed by a key node handler. • The first handler changes the color of the key node that matches the key pressed. The second handler responds to the left and right arrow keys and moves the focus. • Example 4-4 shows the installEventHandler() method that defines the handlers for the keyboard node. Example 4-4 Handlers for the Keyboard Node private void installEventHandler(final Parent keyboardNode) { // handler for key pressed / released events not handled by
  • 22. // key nodes final EventHandler<KeyEvent> keyEventHandler = new EventHandler<KeyEvent>() { public void handle(final KeyEvent keyEvent) { final Key key = lookupKey(keyEvent.getCode()); if (key != null) { key.setPressed(keyEvent.getEventType() == KeyEvent.KEY_PRESSED); keyEvent.consume(); } } }; keyboardNode.setOnKeyPressed(keyEventHandler); keyboardNode.setOnKeyReleased(keyEventHandler); keyboardNode.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() { public void handle( final KeyEvent keyEvent) { handleFocusTraversal( keyboardNode, keyEvent); } }); } The two handlers for the key-pressed event are considered peer handlers. Therefore, even though each handler consumes the event, the other handler is still invoked. Event handlers for keyboard events include setOnKeyPressed and setOnKeyReleased. Example 2-3 shows samples of these event handlers. Example 2-3 Sample Event Handlers for Keyboard Events final TextField textBox = new TextField();
  • 23. textBox.setPromptText("Write here"); textBox.setOnKeyPressed(new EventHandler<KeyEvent>() { public void handle(KeyEvent ke) { System.out.println("Key Pressed: " + ke.getText()); } }); textBox.setOnKeyReleased(new EventHandler<KeyEvent>() { public void handle(KeyEvent ke) { System.out.println("Key Released: " + ke.getText()); } }); 2. Handling Key and Mouse Events 2.1 Handling Events • In JavaFX applications, events are notifications that something has happened. • As a user clicks a button, presses a key, moves a mouse, or performs other actions, events are dispatched. • Registered event filters and event handlers within the application receive the event and provide a response. 2.2 Processing Events • Processing Events describes events and the handling of events in JavaFX
  • 24. applications, event types, event targets, event capturing, event bubbling, and the underlying architecture of the event processing system. • Events are used to notify your application of actions taken by the user and enable the application to respond to the event. • The JavaFX platform provides the structure for capturing an event, routing the event to its target, and enabling the application to handle the event as needed. Mouse Events Convenience methods for registering event handlers for mouse events include setOnMouseEntered, setOnMouseExited, and setOnMousePressed. The below example shows samples of these event handlers: Sample Event Handlers for Mouse Events final Circle circle = new Circle(radius, Color.RED); circle.setOnMouseEntered(new EventHandler<MouseEvent>() { public void handle(MouseEvent me) { System.out.println("Mouse entered"); } }); circle.setOnMouseExited(new EventHandler<MouseEvent>() { public void handle(MouseEvent me) { System.out.println("Mouse exited"); } }); circle.setOnMousePressed(new EventHandler<MouseEvent>() { public void handle(MouseEvent me) { System.out.println("Mouse pressed"); } }); To see how similar event handlers are used, run the Ensemble sample, which is
  • 25. available in the JavaFX samples that can be downloaded from the JDK Demos and Samples section of the Java SE Downloads page. The Ensemble sample also provides the source code for the event handlers. Controls: How JavaFX is designed? • JavaFX is somewhat inspired by Flash / Flex. Some of the same ideas are found in JavaFX. • In general, a JavaFX application contains one or more stages which correspond to windows. Each stage has a scene attached to it. • Each scene can have an object graph of controls, layouts etc. attached to it, called the scene graph. Here is an illustration of the general structure of a JavaFX application: Stage • The stage is the outer frame for a JavaFX application. • The stage typically corresponds to a window. • In the early days where JavaFX could run in the browser, the stage could also refer to the area inside the web page that JavaFX had available to draw itself.
  • 26. • Since the deprecation of the Java browser plugin JavaFX is mostly used for desktop applications. • Here, JavaFX replaces Swing as the recommended desktop GUI framework. • And I must say, that JavaFX looks a whole lot more consistent and feature rich than Swing. • When used in a desktop environment, a JavaFX application can have multiple windows open. Each window has its own stage. • Each stage is represented by a Stage object inside a JavaFX application. • A JavaFX application has a primary Stage object which is created for you by the JavaFX runtime. • A JavaFX application can create additional Stage objects if it needs additional windows open. For instance, for dialogs, wizards etc. Scene • To display anything on a stage in a JavaFX application, you need a scene. • A stage can only show one scene at a time, but it is possible to exchange the scene at runtime. • Just like a stage in a theater can be rearranged to show multiple scenes during a play, a stage object in JavaFX can show multiple scenes (one at a time) during the life time of a JavaFX application. • You might wonder why a JavaFX application would ever have more than one scene per stage. Imagine a computer game. • A game might have multiple "screens" to show to the user. For instance, an initial menu screen, the main game screen (where the game is played), a game over screen and a high score screen. • Each of these screens can be represented by a different scene. • When the game needs to change from one screen to the next, it simply attaches the corresponding scene to the Stage object of the JavaFX application. • A scene is represented by a Scene object inside a JavaFX application. A JavaFX application must create all Scene objects it needs. Scene Graph
  • 27. • All visual components (controls, layouts etc.) must be attached to a scene to be displayed, and that scene must be attached to a stage for the whole scene to be visible. • The total object graph of all the controls, layouts etc. attached to a scene is called the scene graph. Nodes • All components attached to the scene graph are called nodes. • All nodes are subclasses of a JavaFX class called javafx.scene.Node . • There are two types of nodes: Branch nodes and leaf nodes. • A branch node is a node that can contain other nodes (child nodes). • Branch nodes are also referred to as parent nodes because they can contain child nodes. • A leaf node is a node which cannot contain other nodes. Controls • JavaFX controls are JavaFX components which provide some kind of control functionality inside a JavaFX application. • For instance, a button, radio button, table, tree etc. • For a control to be visible it must be attached to the scene graph of some Scene object. • Controls are usually nested inside some JavaFX layout component that manages the layout of controls relative to each other. JavaFX contains the following controls: • Accordion • Button • CheckBox • ChoiceBox • ColorPicker
  • 28. • ComboBox • DatePicker • Label • ListView • RadioButton • Slider • Spinner • SplitMenuButton • SplitPane • TableView • TabPane • TextArea • TextField • TitledPane • ToggleButton • ToolBar • TreeTableView • TreeView JAVAFX - Controls BUTTONS CONTROL: 1. Checkbox, 2. ToggleButton 3. RadioButtons 4. ToggleButton 5. RadioButtons
  • 29. LIST AND COMBO CONTROLS 1. ListView 2. ComboBox 3. ChoiceBox 4. Checkbox 5. ListView 6. ComboBox Layouts • JavaFX layouts are components which contains other components inside them. • The layout component manages the layout of the components nested inside it. • JavaFX layout components are also sometimes called parent components because they contain child components, and because layout components are subclasses of the JavaFX class javafx.scene.Parent. • A layout component must be attached to the scene graph of some Scene object to be visible. JavaFX contains the following layout components: • Group • Region Each of these layout components will be covered in separate texts. Layouts – ScrollPane - FlowPane – HBox and VBox – BorderPane – StackPane – GridPane. • Pane
  • 30. • HBox • VBox • FlowPane • BorderPane • StackPane • TilePane • GridPane • AnchorPane • TextFlow Nested Layouts • It is possible to nest layout components inside other layout components. • This can be useful to achieve a specific layout. • For instance, to get horizontal rows of components which are not laid out in a grid, but differently for each row, you can nest multiple HBox layout components inside a VBox component. TEXT CONTROLS JavaFX Text • The JavaFX Text control can display a text inside a JavaFX GUI. • The JavaFX Text control is represented by the JavaFX class javafx.scene.text.Text . • • You can set the font to be used by the Text control, text size, font decorations and many other things.
  • 31. • Since the JavaFX Text control is a subclass of the JavaFX Shape class, the Text class has all the same methods available that other JavaFX Shape objects do - e.g. fill and stroke color and style. • The JavaFX Text control is also a subclass of the JavaFX Node class, o so the Text class also has all the same methods available as any other JavaFX Node has, meaning you can set effects on it etc. JavaFX Text Example Here is a simple, complete JavaFX text example: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; public class TextExample extends Application { public static void main(String[] args) { launch(args); } public void start(Stage primaryStage) { Text text = new Text("This is a JavaFX text."); Scene scene = new Scene(new VBox(text), 300, 250); primaryStage.setScene(scene); primaryStage.show(); } } Set Text You can set the text of a JavaFX Text object via its setText() method. Here is an example of setting the text of a JavaFX Text control via setText():
  • 32. Text text = new Text(); text.setText("This is the text to display"); Set Font You can set the font of a JavaFX Text control via its setFont() method. Here is an example of setting the font of a JavaFX Text object via its setFont() method: Text text = new Text("Some Text"); text.setFont(Font.font("Arial")); This example sets the font to be used by the Text control to render the text to be of the font family Arial. The JavaFX Font class used in this example is the javafx.scene.text.Font class. The Font class actually also lets you specify the font weight and font size. Here is the example above, modified to also set font weight and font size for the JavaFX Text control: Text text = new Text("Some Text"); text.setFont(Font.font("Arial", FontWeight.BOLD, 36)); This example sets the font weight to bold and font size to 36. The FontWeight class used in this example is the javafx.scene.text.FontWeight class. Set Fill Color Being a Shape, you can set the fill color of a JavaFX Text control. The fill color is the "inside" color used to draw the text. You set the fill color of a Text control via its setFill() method which takes a JavaFX Color object as parameter. Here is an example of setting the fill color of a JavaFX Text control via setFill(): text.setFill(Color.YELLOW); Set Stroke Color Being a Shape, you can also set the stroke color of a JavaFX Text control.
  • 33. The stroke color is the "outline" or "boundary" color used to draw the text. By default, text is rendered only using the fill color, but setting a stroke color can add a nice effect. You set the stroke color of a Text control via its setStroke() method which takes a JavaFX Color object as parameter. Here is an example of setting the stroke color of a JavaFX Text control via setStroke(): text.setStroke(Color.GREEN); Text X and Y Position The X and Y position of a JavaFX Text control determines where inside its parent container element the Text control is displayed - provided the parent container respects this position (Pane does, VBox does not). You can set the X and Y position of a Text control via its methods setX() and setY(). Here is an example of setting the X and Y position of a JavaFX Text control: text.setX(50); text.setY(25); Text Origin The JavaFX Text control has an origin which controls how the text is displayed relative to the Y position of the Text control. You set the origin using the Text setTextOrigin() method. Here is an example of setting the Text origin: text.setTextOrigin(VPos.BASELINE); The setTextOrigin() method takes a VPos parameter. The VPos class contains the following constants you can choose between: i) VPos.BASELINE ii) VPos.BOTTOM
  • 34. iii)VPos.CENTER iv) VPos.TOP i) VPos.BASELINE means that the Y position of the Text control is interpreted to mean the Y baseline of the displayed text. The text is displayed just above the baseline, with some characters extending below the baseline. ii) VPos.BOTTOM means that the Y position of the Text control is interpreted to mean the bottom the displayed text. This is lower than BASELINE. iii) VPos.CENTER means that the Y position of the Text control is interpreted to mean the center of the text vertically. iv) VPos.TOP means that the Y position of the Text control is interpreted to mean the top of the text vertically. Multiline Text The JavaFX Text control will break the text it displays on to multiple lines based on these rules: i) If the text contains a line break ( n ) . ii) If the text width exceeds a wrapping width set on the Text control. Here is first an example showing a text that contains a line break: Text text = new Text("This is a JavaFX text.nLine 2"); The Text control will break the text before "Line" because the String contains a line break character. Here is an example of setting a text wrapping width on the JavaFX Text control: Text text = new Text("This is a longer JavaFX text."); text.setWrappingWidth(80); • The JavaFX Text control will attempt to break the text between words. • Thus, if after a specific word the text width is wider than the wrapping width,
  • 35. the Text control will wrap the text before that word that makes the text wider than the wrapping width. Text Strikethrough • The JavaFX Text control enables you to apply a strikethrough decoration to the text it displays. You enable the strikethrough decoration via the Text setStrikethrough() method, passing a value of true as parameter. A parameter value of false will disable the strikethrough effect. Here is an example of enabling the JavaFX Text strikethrough decoration via the setStrikethrough() method: text.setStrikethrough(true); Text Underline The JavaFX Text control enables you to apply an underline decoration to the text it displays. You enable the underline decoration via the Text setUnderline() method, passing a value of true as parameter. A parameter value of false will disable the underline decoration. Here is an example of enabling the JavaFX Text underline decoration via the setUnderline() method: text.setUnderline(true); Font Smoothing Techniques • The JavaFX Text control contains two different font smoothing (antialiasing) techniques you can choose between. • The first technique is called LCD, and the second is called GRAY. • You can choose which font smoothing technique the Text control should use via the setFontSmoothingType() method. Here are examples of setting both LCD and GRAY as font smoothing technique on a JavaFX Text control: text.setFontSmoothingType(FontSmoothingType.GRAY);
  • 36. text.setFontSmoothingType(FontSmoothingType.LCD); Which of the two font smoothing techniques fits best to your application you will have to experiment with. JavaFX Fonts • Create Font Instance • Using the Font Instance • List Installed Font Families and Names Jakob Jenkov Last update: 2020-11-14 The JavaFX Font class, java.scene.text.Font, enables you to load different Fonts for use in your JavaFX applications. A font is a text style. All text rendered with the same font will look similar. In this JavaFX Font tutorial I will show you how to load and set fonts in JavaFX. Create Font Instance To use fonts in JavaFX you must create a JavaFX Font instance. The easiest way to create a JavaFX Font instance is to use the static factory methods in the Font class. The following example shows how to create JavaFX Font instances using the many variations of the Font class static factory methods: String fontFamily = "Arial"; double fontSize = 13; FontWeight fontWeight = FontWeight.BOLD; FontPosture fontPosture = FontPosture.ITALIC; Font font1 = Font.font(fontFamily); Font font2 = Font.font(fontSize); Font font3 = Font.font(fontFamily, fontSize); Font font4 = Font.font(fontFamily, fontWeight , fontSize); Font font5 = Font.font(fontFamily, fontPosture, fontSize); Font font6 = Font.font(fontFamily, fontWeight , fontPosture, fontSize);
  • 37. As you can see, the Font factory methods enable you to create Font instances representing different font families, font sizes, font weights and font postures. Using the Font Instance Once you have created a JavaFX Font instance you use it by setting it on whatever JavaFX component capable of using a Font. For instance, you can set it on a JavaFX Text control. Here is an example of setting a Font instance on a Text control: Font font = Font.font("Arial"); Text text = new Text("This is the text"); text.setFont(font); Precisely how a Font object is applied to a given JavaFX control depends on the specific JavaFX control. In the JavaFX Text example the Font object is applied via the Text setFont() method, as shown above. List Installed Font Families and Names The JavaFX Font class provides two methods that can list the font families and font names and installed on the system the JavaFX application is running on. These methods are the getFamilies() and getFontNames() methods. Here are some examples of calling these methods: List<String> fontFamilies = Font.getFamilies(); List<String> fontNames = Font.getFontNames(); Both font family names and font names can be used when creating a Font instance. Provide either the font family name or font name in the Font factory method fontFamily parameter. To see the actual names, loop through the lists above and print out their names, like this: for(String item : fontFamilies) { System.out.println(item); } for(String item : fontNames) { System.out.println(item);
  • 38. } BUTTONS JavaFX Button A JavaFX Button control enables a JavaFX application to have some action executed when the application user clicks the button. The JavaFX Button control is represented by the class javafx.scene.control.Button . A JavaFX Button can have a text and an icon on it which indicate to the user what clicking the button will do. Creating a Button You create a button control by creating an instance of the Button class. Here is a JavaFX Button instantiation example: Button button = new Button("My Label"); The text to be displayed on the button is passed as parameters to the Button constructor. Adding a Button to the Scene Graph For a JavaFX Button to be visible the button object must be added to the scene graph. This means adding it to a Scene object, or as child of a layout which is attached to a Scene object. Here is an example that attaches a JavaFX Button to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.stage.Stage;
  • 39. public class ButtonExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("HBox Experiment 1"); Button button = new Button("My Button"); Scene scene = new Scene(button, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } Notice that the Button is added directly to the Scene object. Normally you would nest the Button inside a layout component of some kind. I have left that out here to keep the example simple. See the tutorials about layout components to see how they work. The result of running the above JavaFX Button example is an application that looks like this: Notice that the button takes up all the space available in the window. That is why it is hard to see the edges of the button. When a JavaFX button is added to a layout component you can more easily see the edges of the button. Button Text
  • 40. There are two ways to set the text of a JavaFX button. The first way is to pass the text to the Button constructor. You have already seen this in earlier examples. The second way to set the button text is by calling the setText() method on the Button instance. This can be done after the Button instance is created. Thus it can be used to change the text of a Button that is already visible. Here is an example how how calling setText() on a JavaFX Button looks: button.setText("Click me if you dare!"); Button Text Size You can set the text size of a JavaFX Button. You do so using the CSS property -fx-text-size. This CSS property is explained in the section about Button CSS Styling Button Text Wrap The JavaFX Button control supports text wrapping of the button text. By text wrapping is meant that if the text is too long to be displayed on a single line inside the button, the text is broken onto multiple lines. You enable text wrapping on a JavaFX Button instance using the method setWrapText(). The setWrapText() method takes a single boolean parameter. If you pass a value of true to setWrapText() then you enable text wrapping. If you pass a value of false to setWrapText() then you disable text wrapping. Here is an example that enables text wrapping on a JavaFX button: button.setWrapText(true); Here is a screenshot of two JavaFX buttons one of which has text wrapping enabled: Button Font
  • 41. You can specify what font the text on a JavaFX Button should be rendered with via its setFont() method. You can read more about creating fonts in my JavaFX Fonts tutorial. Here is an example of setting a font on a JavaFX Button: Button button = new Button("Click me!"); Font font = Font.font("Courier New", FontWeight.BOLD, 36); button.setFont(font); Default Button Mode A JavaFX Button can be set into a default mode. When a Button is in default mode it is rendered differently, so the user can see that this is the default button. On Windows, the Button's background color changes, although I guess that also depends on the color theme used in the application etc. and may change in future versions of JavaFX. The default button is intended to be used for the "default choice" in a dialog or form. Thus, it becomes easier for the user to select the choice that the user is most likely making most often. The default button of a dialog or form has some additional keyboard shortcuts to help the user click it: • Windows + Linux o If no other button has focus, pressing the ENTER keyboard key will activate the default button. o If the default button has focus, pressing the ENTER keyboard key will activate the default button. • Mac o Only the default button can be activated by pressing the ENTER keyboard key. All other buttons are activated by pressing the the SPACE keyboard key. Setting a JavaFX Button as the default button is done via its setDefaultButton() method. Here is an example of setting a JavaFX button as default button: button.setDefaultButton(true); Cancel Button Mode
  • 42. A JavaFX Button can be set into cancel mode. When a Button is in cancel mode it can be activated more easily by pressing the ESC keyboard key - if no other node in the Scene graph consumes this key press. Setting a JavaFX Button in cancel mode (as cancel button) is done via its setCancelButton() method. Here is an example of setting a JavaFX Button in cancel mode: buttonDefault.setCancelButton(true); Button Image It is possible to display an image inside a button next to the button text. The JavaFX Button class contains a constructor that can take a Node as extra parameter. Here is a JavaFX label example that adds an image to the button using an JavaFX ImageView component: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; import java.io.FileInputStream; public class ButtonExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("HBox Experiment 1"); FileInputStream input = new FileInputStream("resources/images/iconmonstr-home-6- 48.png"); Image image = new Image(input); ImageView imageView = new ImageView(image);
  • 43. Button button = new Button("Home", imageView); Scene scene = new Scene(button, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The result of running the above JavaFX Button example is an application that looks like this: Button Size The JavaFX Button class contains a set of methods you can use to set the button size. The methods controlling the button size are: button.setMinWidth() button.setMaxWidth() button.setPrefWidth() button.setMinHeight() button.setMaxHeight() button.setPrefHeight() button.setMinSize() button.setMaxSize()
  • 44. button.setPrefSize() The methods setMinWidth() and setMaxWidth() sets the minimum and maximum width the button should be allowed to have. The method setPrefWidth() sets the preferred width of the button. When there is space enough to display a button in its preferred width, JavaFX will do so. If not, JavaFX will scale the button down until it reaches its minimum width. The methods setMinHeight() and setMaxHeight() sets the minimum and maximum height the button should be allowed to have. The method setPrefHeight() sets the preferred height of the button. When there is space enough to display a button in its preferred height, JavaFX will do so. If not, JavaFX will scale the button down until it reaches its minimum height. The methods setMinSize(), setMaxSize() and setPrefSize() sets both width and height for the button in a single call. Thus, these methods takes both a width and a height parameter. For instance, calling button.setMaxSize(100, 200); is equivalent to calling button.setMaxWidth(100); button.setMaxHeight(200); Here is a screenshot of two JavaFX buttons. The first button has the default size calculated from its button text and the layout component it is nested inside. The second button has a preferred width of 200 and height of 48 set on it: Button Events In order to respond to the click of a button you need to attach an event listener to the Button object. Here is how that looks:
  • 45. button.setOnAction(new EventHandler() { @Override public void handle(ActionEvent actionEvent) { //... do something in here. } }); Here is how attaching a click event listener looks with a Java Lambda expression: button.setOnAction(actionEvent -> { //... do something in here. }); Finally, let us see a full example that changes the text of a JavaFX Label when the button is clicked: package com.jenkov.javafx.controls; 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.stage.Stage; public class ButtonExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("HBox Experiment 1"); Label label = new Label("Not clicked"); Button button = new Button("Click"); button.setOnAction(value -> {
  • 46. label.setText("Clicked!"); }); HBox hbox = new HBox(button, label); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } Button Mnemonic You can set a mnemonic on a JavaFX Button instance. A mnemonic is a keyboard key which activates the button when pressed in conjunction with the ALT key. Thus, a mnemonic is a keyboard shortcut to activating the button. I will explain how to activate a button via its mnemonic later. The mnemonic for a button is specified inside the button text. You mark which key is to be used as mnemonic by placing an underscore character (_) in front of the character in the button text you want to set as mnemonic for that button. The underscore character will not be displayed in the button text. Here is an example setting a mnemonic for a button: button.setMnemonicParsing(true); button.setText("_Click"); Notice that it is necessary to first call setMnemonicParsing() on the button with a value of true. This instructs the button to parse mnemonics in the button text. If you call this method with a value of false instead, the underscore character in the button text will just show up as text, and will not be interpreted as a mnemonic.
  • 47. The second line sets the text _Click on the button. This tells the button to use the key c as mnemonic. Mnemonics are case insensitive, so it does not have to be an a uppercase C that activates the button. To activate the button you can now press ALT-C (both at the same time). That will activate the button just as if you had clicked it with the mouse. You can also first press the ALT key once. That will show the mnemonic of the button in the button text. You can then press the c key. If you press ALT and then ALT again, the mnemonic is first shown, then hidden again. When the mnemonic is visible you can activate the button with the mnemonic key alone, without ALT pressed at the same time. When the mnemonic is not visible you have to press both ALT and the mnemonic key at the same time to activate the button. Here are two screenshots showing what it looks like when the mnemonic is invisible and visible: Button CSS Styles You can style a JavaFX button using CSS styles. The JavaFX Button control supports the following CSS styles: -fx-border-width -fx-border-color -fx-background-color -fx-font-size -fx-text-fill Here is an example setting the background color of a JavaFX button to red: Button button = new Button("My Button");
  • 48. button.setStyle("-fx-background-color: #ff0000; "); This example sets the style directly on the button via the setStyle() method, but you can also style a JavaFX button via style sheets. See my JavaFX CSS Styling tutorial for more information about using CSS stylesheets with JavaFX. Here is a JavaFX button example which creates 4 different buttons. Each button has a CSS style set on them. After the code example I have included a screenshot of how the buttons look with the given styling. package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.io.FileInputStream; import java.io.FileNotFoundException; public class ButtonExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("Button Experiment 1"); Button button1 = new Button("Button 1"); Button button2 = new Button("Button 2"); Button button3 = new Button("Button 3"); Button button4 = new Button("Button 4"); button1.setStyle("-fx-border-color: #ff0000; -fx-border-width: 5px;"); button2.setStyle("-fx-background-color: #00ff00"); button3.setStyle("-fx-font-size: 2em; "); button4.setStyle("-fx-text-fill: #0000ff");
  • 49. HBox hbox = new HBox(button1, button2, button3, button4); Scene scene = new Scene(hbox, 400, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } Here is a screenshot of the 4 JavaFX buttons with their CSS styling: The first button has both the -fx-border-width and -fx-border-color CSS properties set. This results in a 5 pixel wide red border for the button. The second button has the -fx-background-color CSS property set. This results in a green background color for the button. The third button has the -fx-font-size CSS property set. This results in a button with a text that is 2 times as big as normal. The fourth button has the -fx-text-fill CSS property set. This results in a button with a blue text color. You can combine the CSS styles for a JavaFX button simply by setting multiple CSS properties on it, like the first button in the example above has. Disable Button
  • 50. You can disable a JavaFX Button via its setDisable() method. The setDisable() method takes a boolean parameter which specify if the button should be disabled or not. A value of true means the button will be disabled, and a value of false means it will not be disabled - which means enabled. Here is an example of disabling a JavaFX Button via its setDisable() method: Button button = new Button(); button.setText("Click me!"); // here the app is running, and something happens so // the button should now be disabled. button.setDisable(true); // again the app runs, and something happens so // the button should now be enabled again. button.setDisable(false); Button FXML It is possible to declare a JavaFX Button inside a JavaFX FXML file. I will not explain FXML in every detail here. Click on the link in the first sentence to read more about how FXML works. I will just show you the parts of FXML related to the JavaFX Button control. Here is a very simple FXML file example that shows how to declare a Button: <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.layout.VBox?> <?import javafx.scene.control.Button?> <VBox xmlns:fx="http://javafx.com/fxml" spacing="20"> <children> <Button fx:id="button1" text="Click me!" onAction="#buttonClicked"/> </children> </VBox> It is the <Button> element that declares the Button control. The fx:id attribute can be used to wire up the declared Button to a Button member variable inside an FXML Controller object.
  • 51. The text attribute is used to set the corresponding text property value in the Button instance created for this Button declaration. That is the text displayed on the button. The onAction attribute is used to link the Button's onAction event to a method in the FXML controller object. In this example it is the method named buttonClicked() in the FXML controller. Here is how the corresponding FXML controller object's class looks. Notice the name of the button1 Button member variable matches the fx:id attribute value in the FXML file. This member variable must be public, by the way. Notice also the method buttonClicked() which is referenced from the Button onAction attribute in the FXML file. import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Button; public class ButtonFXMLController { public Button button1 = null; private int button1ClickCount = 0; @FXML public void buttonClicked(Event e){ this.button1ClickCount++; String text = "Button1 clicked " + this.button1ClickCount + " times"; System.out.println(text); button1.setText(text); } } And here is the full JavaFX app that loads the FXML file and creates the FXML controller etc. : import javafx.application.Application; import javafx.fxml.FXMLLoader;
  • 52. import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.io.File; import java.net.URL; public class ButtonFXMLExample extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { FXMLLoader loader = new FXMLLoader(); ButtonFXMLController controller = new ButtonFXMLController(); loader.setController(controller); File fxmlFile = new File("assets/fxml/button-example.fxml"); URL fxmlUrl = fxmlFile.toURI().toURL(); loader.setLocation(fxmlUrl); VBox vbox = loader.<VBox>load(); Scene scene = new Scene(vbox); primaryStage.setScene(scene); primaryStage.setTitle("Button FXML Example"); primaryStage.setWidth(300); primaryStage.setHeight(300); primaryStage.show(); } } Button Transformations
  • 53. You can add JavaFX transformations to a JavaFX Button such as scaling, rotation, translation etc. You add transformation objects to a JavaFX Button like this: button.getTransforms().add(scaleTransformation); Here is a full example of adding a Scale transformation to a JavaFX Button: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.VBox; import javafx.scene.transform.Scale; import javafx.stage.Stage; public class ButtonTransformationExample extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { Button button = new Button(); button.setText("Click me!"); button.setOnAction((event) -> { System.out.println("Button clicked!"); }); Scale scaleTransformation = new Scale(); scaleTransformation.setX(3.0); scaleTransformation.setY(2.0); scaleTransformation.setPivotX(0); scaleTransformation.setPivotY(0); button.getTransforms().add(scaleTransformation);
  • 54. VBox vbox = new VBox(button); Scene scene = new Scene(vbox); primaryStage.setScene(scene); primaryStage.setWidth(512); primaryStage.setHeight(256); primaryStage.show(); } }
  • 55. JavaFX ToggleButton A JavaFX ToggleButton is a button that can be selected or not selected. Like a button that stays in when you press it, and when you press it the next time it comes out again. Toggled - not toggled. The JavaFX ToggleButton is represented by the class javafx.scene.control.ToggleButton . Creating a ToggleButton You create a JavaFX ToggleButton by creating an instance of the ToggleButton class. Here is an example of creating a JavaFX ToggleButton instance: ToggleButton toggleButton1 = new ToggleButton("Left"); This example creates a ToggleButton with the text Left on. Adding a ToggleButton to the Scene Graph To make a ToggleButton visible you must add it to the JavaFX scene graph. This means adding it to a Scene, or as child of a layout which is attached to a Scene object. Here is an example that attaches a JavaFX ToggleButton to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ToggleButton; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class ToggleButtonExperiments extends Application {
  • 56. @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("HBox Experiment 1"); ToggleButton toggleButton1 = new ToggleButton("Left"); HBox hbox = new HBox(toggleButton1); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The application resulting from running the above example code is illustrated in the following two screenshots. The first screenshot shows a ToggleButton which is not pressed, and the second screenshot shows the same ToggleButton pressed (selected, activated etc.): ToggleButton Text You can set or change the text of a JavaFX ToggleButton via its setText() method. Here is an example of changing the text of a JavaFX ToggleButton via setText(): ToggleButton toggleButton = new ToggleButton("Toggle This!"); toggleButton.setText("New Text");
  • 57. ToggleButton Font You can set the font to use to render the button text of a JavaFX ToggleButton via its setFont() method. You can read more about creating fonts in my JavaFX Fonts tutorial. Here is an example of setting the font of a JavaFX ToggleButton: ToggleButton toggleButton = new ToggleButton("Toggle This!"); Font arialFontBold36 = Font.font("Arial", FontWeight.BOLD, 36); toggleButton.setFont(arialFontBold36); Reading Selected State The ToggleButton class has a method named isSelected which lets you determine if the ToggleButton is selected (pressed) or not. The isSelected() method returns a boolean with the value true if the ToggleButton is selected, and false if not. Here is an example: boolean isSelected = toggleButton1.isSelected(); ToggleGroup You can group JavaFX ToggleButton instances into a ToggleGroup. A ToggleGroup allows at most one ToggleButton to be toggled (pressed) at any time. The ToggleButton instances in a ToggleGroup thus functions similarly to radio buttons. Here is a JavaFX ToggleGroup example: ToggleButton toggleButton1 = new ToggleButton("Left"); ToggleButton toggleButton2 = new ToggleButton("Right"); ToggleButton toggleButton3 = new ToggleButton("Up"); ToggleButton toggleButton4 = new ToggleButton("Down"); ToggleGroup toggleGroup = new ToggleGroup(); toggleButton1.setToggleGroup(toggleGroup); toggleButton2.setToggleGroup(toggleGroup); toggleButton3.setToggleGroup(toggleGroup); toggleButton4.setToggleGroup(toggleGroup);
  • 58. Here is a full example that adds the 4 ToggleButton instances to a ToggleGroup, and adds them to the scene graph too: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class ToggleButtonExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("HBox Experiment 1"); ToggleButton toggleButton1 = new ToggleButton("Left"); ToggleButton toggleButton2 = new ToggleButton("Right"); ToggleButton toggleButton3 = new ToggleButton("Up"); ToggleButton toggleButton4 = new ToggleButton("Down"); ToggleGroup toggleGroup = new ToggleGroup(); toggleButton1.setToggleGroup(toggleGroup); toggleButton2.setToggleGroup(toggleGroup); toggleButton3.setToggleGroup(toggleGroup); toggleButton4.setToggleGroup(toggleGroup); HBox hbox = new HBox(toggleButton1, toggleButton2, toggleButton3, toggleButton4); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The resulting applications looks like this:
  • 59. Reading Selected State of a ToggleGroup You can read which ToggleButton of a ToggleGroup is selected (pressed) using the getSelectedToggle() method, like this: ToggleButton selectedToggleButton = (ToggleButton) toggleGroup.getSelectedToggle(); If no ToggleButton is selected the getSelectedToggle() method returns null . JavaFX RadioButton A JavaFX RadioButton is a button that can be selected or not selected. The RadioButton is very similar to the JavaFX ToggleButton, but with the difference that a RadioButton cannot be "unselected" once selected. If RadioButtons are part of a ToggleGroup then once a RadioButton has been selected for the first time, there must be one RadioButton selected in the ToggleGroup .
  • 60. The JavaFX RadioButton is represented by the class javafx.scene.control.RadioButton. The RadioButton class is a subclass of the ToggleButton class. Creating a RadioButton You create a JavaFX RadioButton using its constructor. Here is a JavaFX RadioButton instantiation example: RadioButton radioButton1 = new RadioButton("Left"); The String passed as parameter to the RadioButton constructor is displayed next to the RadioButton. Adding a RadioButton to the Scene Graph To make a RadioButton visible you must add it to the scene graph of your JavaFX application. This means adding the RadioButton to a Scene, or as child of a layout which is attached to a Scene object. Here is an example that attaches a JavaFX RadioButton to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.RadioButton; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class RadioButtonExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("HBox Experiment 1"); RadioButton radioButton1 = new RadioButton("Left"); HBox hbox = new HBox(radioButton1); Scene scene = new Scene(hbox, 200, 100);
  • 61. primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The application resulting from running this example looks like this: Reading Selected State The RadioButton class has a method named isSelected which lets you determine if the RadioButton is selected or not. The isSelected() method returns a boolean with the value true if the RadioButton is selected, and false if not. Here is an example: boolean isSelected = radioButton1.isSelected(); ToggleGroup You can group JavaFX RadioButton instances into a ToggleGroup. A ToggleGroup allows at most one RadioButton to be selected at any time. Here is a JavaFX ToggleGroup example: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.HBox;
  • 62. import javafx.stage.Stage; public class RadioButtonExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("HBox Experiment 1"); RadioButton radioButton1 = new RadioButton("Left"); RadioButton radioButton2 = new RadioButton("Right"); RadioButton radioButton3 = new RadioButton("Up"); RadioButton radioButton4 = new RadioButton("Down"); ToggleGroup radioGroup = new ToggleGroup(); radioButton1.setToggleGroup(radioGroup); radioButton2.setToggleGroup(radioGroup); radioButton3.setToggleGroup(radioGroup); radioButton4.setToggleGroup(radioGroup); HBox hbox = new HBox(radioButton1, radioButton2, radioButton3, radioButton4); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The application resulting from running this example looks like this: Reading Selected State of a ToggleGroup
  • 63. You can read which RadioButton of a ToggleGroup is selected using the getSelectedToggle() method, like this: RadioButton selectedRadioButton = (RadioButton) toggleGroup.getSelectedToggle(); If no RadioButton is selected the getSelectedToggle() method returns null . Draggable Panels Example The Draggable Panels example demonstrates the following uses of filters: • Registering a filter for a super-type event to provide common handling for subtype events • Consuming an event to prevent a child node from acting on it Figure 3-1 is the screen that is shown when the Draggable Panels example is started. The user interface consists of three panels. Each panel contains different UI controls. At the bottom of the screen is a check box that controls whether the panels can be dragged. Figure 3-1 Initial Screen for the Draggable Panels Example Description of "Figure 3-1 Initial Screen for the Draggable Panels Example" If the check box is not selected, clicking any of the controls in the panels generates a response from the control. If the check box is selected, the individual controls do not respond to mouse clicks. Instead, clicking anywhere within a panel and dragging the mouse moves the entire panel, enabling you to change the position of the panels as shown in Figure 3-2. Figure 3-2 Screen with Repositioned Panels
  • 64. Description of "Figure 3-2 Screen with Repositioned Panels" Filters for the Draggable Panels Example In the Draggable Panels example, the makeDraggable() method is used in the creation of the three panels to make each panel movable. This method and the filter definitions are shown in Example 3-3. Example 3-3 Filter Definitions in makeDraggable() private Node makeDraggable(final Node node) { final DragContext dragContext = new DragContext(); final Group wrapGroup = new Group(node); wrapGroup.addEventFilter( MouseEvent.ANY, new EventHandler<MouseEvent>() { public void handle(final MouseEvent mouseEvent) { if (dragModeActiveProperty.get()) { // disable mouse events for all children mouseEvent.consume(); }
  • 65. } }); wrapGroup.addEventFilter( MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() { public void handle(final MouseEvent mouseEvent) { if (dragModeActiveProperty.get()) { // remember initial mouse cursor coordinates // and node position dragContext.mouseAnchorX = mouseEvent.getX(); dragContext.mouseAnchorY = mouseEvent.getY(); dragContext.initialTranslateX = node.getTranslateX(); dragContext.initialTranslateY = node.getTranslateY(); } } }); wrapGroup.addEventFilter( MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() { public void handle(final MouseEvent mouseEvent) { if (dragModeActiveProperty.get()) { // shift node from its initial position by delta
  • 66. // calculated from mouse cursor movement node.setTranslateX( dragContext.initialTranslateX + mouseEvent.getX() - dragContext.mouseAnchorX); node.setTranslateY( dragContext.initialTranslateY + mouseEvent.getY() - dragContext.mouseAnchorY); } } }); return wrapGroup; } Filters for the following events are defined and registered for each panel: • MouseEvent.ANY. This filter processes all mouse events for the panel. If the Drag Mode check box is selected, the filter consumes the event, and the child nodes, which are the UI controls within the panel, do not receive the event. If the check box is not selected, the control at the location of the mouse cursor processes the event. • MouseEvent.MOUSE_PRESSED. This filter processes only mouse-pressed events for the panel. If the Drag Mode check box is selected, the current location of the mouse is stored. • MouseEvent.MOUSE_DRAGGED. This filter processes only mouse-dragged events for the panel. If the Drag Mode check box is selected, the panel is moved. Note that a panel has three registered filters. Filters for specific event types are invoked before super-type events, so the filters for MouseEvent.MOUSE_PRESSED and MouseEvent.MOUSE_DRAGGED are invoked before the filter for MouseEvent.ANY.
  • 67. JavaFX CheckBox A JavaFX CheckBox is a button which can be in three different states: Selected, not selected and unknown (indeterminate). The JavaFX CheckBox control is represented by the class javafx.scene.control.CheckBox. Creating a CheckBox You create a JavaFX CheckBox control via the CheckBox constructor. Here is a JavaFX CheckBox instantiation example: CheckBox checkBox1 = new CheckBox("Green"); The String passed to the CheckBox constructor is displayed next to the CheckBox control. Adding a CheckBox to the Scene Graph To make a JavaFX CheckBox control visible you must add it to the scene graph of your JavaFX application. That means adding the CheckBox control to a Scene object, or to some layout component which is itself added to a Scene object. Here is an example showing how to add a CheckBox to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.layout.HBox; import javafx.stage.Stage;
  • 68. public class CheckBoxExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("CheckBox Experiment 1"); CheckBox checkBox1 = new CheckBox("Green"); HBox hbox = new HBox(checkBox1); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The application resulting from running this code looks like this: Reading Selected State You can read the selected state of a CheckBox via its method isSelected(). Here is an example of how calling isSelected() looks: boolean isSelected = checkBox1.isSelected(); Allowing Indeterminate State
  • 69. As mentioned earlier a JavaFX CheckBox can be in an indeterminate state which means that is is neither selected, nor not selected. The user simply has not interacted with the CheckBox yet. By default a CheckBox is not allowed to be in the indeterminate state. You can set if a CheckBox is allowed to be in an indeterminate state using the method setAllowIndeterminate(). Here is an example of allowing the indeterminate state for a CheckBox: checkBox1.setAllowIndeterminate(true); Reading Indeterminate State You can read if a CheckBox is in the indeterminate state via its isIndeterminate() method. Here is an example of checking if a CheckBox is in the indeterminate state: boolean isIndeterminate = checkBox1.isIndeterminate(); Note, that if a CheckBox is not in the indeterminate state, it is either selected or not selected, which can be seen via its isSelected() method JavaFX ChoiceBox The JavaFX ChoiceBox control enables users to choose an option from a predefined list of choices. The JavaFX ChoiceBox control is represented by the class javafx.scene.control.ChoiceBox . This JavaFX ChoiceBox tutorial will explain how to use the ChoiceBox class. Creating a ChoiceBox You create a ChoiceBox simply by creating a new instance of the ChoiceBox class. Here is a JavaFX ChoiceBox instantiation example:
  • 70. ChoiceBox choiceBox = new ChoiceBox(); Adding Choices to a ChoiceBox You can add choices to a ChoiceBox by obtaining its item collection and add items to it. Here is an example that adds choices to a JavaFX ChoiceBox : choiceBox.getItems().add("Choice 1"); choiceBox.getItems().add("Choice 2"); choiceBox.getItems().add("Choice 3"); Adding a ChoiceBox to the Scene Graph To make a ChoiceBox visible you must add it to the scene graph. This means that you must add the ChoiceBox to a Scene object or to some layout component which is then attached to the Scene object. Here is an example showing how to add a JavaFX ChoiceBox to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ChoiceBox; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class ChoiceBoxExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("ChoiceBox Experiment 1"); ChoiceBox choiceBox = new ChoiceBox(); choiceBox.getItems().add("Choice 1"); choiceBox.getItems().add("Choice 2"); choiceBox.getItems().add("Choice 3"); HBox hbox = new HBox(choiceBox); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show();
  • 71. } public static void main(String[] args) { Application.launch(args); } } The application resulting from running this example would look similar to this: Reading the Selected Value You can read the selected value of a ChoiceBox via its getValue() method. If no choice is selected, the getValue() method returns null. Here is an example of calling getValue(): String value = (String) choiceBox.getValue(); Listening for Selection It is possible to listen for selection changes in a JavaFX ChoiceBox by setting an action listener on the ChoiceBox via its setOnAction() method. Here is an example of setting an action listener on a ChoiceBox which reads what value was selected in the ChoiceBox: ChoiceBox choiceBox = new ChoiceBox(); choiceBox.getItems().add("Choice 1"); choiceBox.getItems().add("Choice 2"); choiceBox.getItems().add("Choice 3"); choiceBox.setOnAction((event) -> { int selectedIndex = choiceBox.getSelectionModel().getSelectedIndex(); Object selectedItem = choiceBox.getSelectionModel().getSelectedItem();
  • 72. System.out.println("Selection made: [" + selectedIndex + "] " + selectedItem); System.out.println(" ChoiceBox.getValue(): " + choiceBox.getValue()); }); JavaFX ComboBox The JavaFX ComboBox control enables users to choose an option from a predefined list of choices, or type in another value if none of the predefined choices matches what the user want to select. The JavaFX ComboBox control is represented by the class javafx.scene.control.ComboBox . This JavaFX ComboBox tutorial will explain how to use the ComboBox class. Creating a ComboBox You create a ComboBox simply by creating a new instance of the ComboBox class. Here is a JavaFX ComboBox instantiation example: ComboBox comboBox = new ComboBox(); Adding Choices to a ComboBox You can add choices to a ComboBox by obtaining its item collection and add items to it. Here is an example that adds choices to a JavaFX ComboBox : comboBox.getItems().add("Choice 1"); comboBox.getItems().add("Choice 2"); comboBox.getItems().add("Choice 3"); Adding a ComboBox to the Scene Graph
  • 73. To make a ComboBox visible you must add it to the scene graph. This means that you must add the ComboBox to a Scene object or to some layout component which is then attached to the Scene object. Here is an example showing how to add a JavaFX ComboBox to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ComboBox; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class ComboBoxExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("ComboBox Experiment 1"); ComboBox comboBox = new ComboBox(); comboBox.getItems().add("Choice 1"); comboBox.getItems().add("Choice 2"); comboBox.getItems().add("Choice 3"); HBox hbox = new HBox(comboBox); Scene scene = new Scene(hbox, 200, 120); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The application resulting from running this example would look similar to this:
  • 74. Making the ComboBox Editable A ComboBox is not editable by default. That means, that by default the user cannot enter anything themselves, but only choose from the predefined list of options. To make a ComboBox editable you must call the setEditable() method of the ComboBox. Here is an example making a JavaFX ComboBox editable: comboBox.setEditable(true); Once the ComboBox is editable the user can type in values into the ComboBox. The entered value is also read via the getValue() method as explained earlier. The following screenthot shows a JavaFX ComboBox which is editable, and with a custom value entered: Reading the Selected Value You can read the selected value of a ComboBox via its getValue() method. If no choice is selected, the getValue() method returns null. Here is an example of calling getValue(): String value = (String) comboBox.getValue();
  • 75. Listening for Selection It is possible to listen for selection changes in a JavaFX ComboBox by setting an action listener on the ComboBox via its setOnAction() method. Here is an example of setting an action listener on a ComboBox which reads what value was selected in the ComboBox: ComboBox comboBox = new ComboBox(); comboBox.getItems().add("Choice 1"); comboBox.getItems().add("Choice 2"); comboBox.getItems().add("Choice 3"); comboBox.setOnAction((event) -> { int selectedIndex = comboBox.getSelectionModel().getSelectedIndex(); Object selectedItem = comboBox.getSelectionModel().getSelectedItem(); System.out.println("Selection made: [" + selectedIndex + "] " + selectedItem); System.out.println(" ComboBox.getValue(): " + comboBox.getValue()); }); JavaFX ListView The JavaFX ListView control enables users to choose one or more options from a predefined list of choices. The JavaFX ListView control is represented by the class javafx.scene.control.ListView . This JavaFX ListView tutorial will explain how to use the ListView class. Creating a ListView You create a ListView simply by creating a new instance of the ListView class. Here is a JavaFX ListView instantiation example: ListView listView = new ListView(); Adding Items to a ListView
  • 76. You can add items (options) to a ListView by obtaining its item collection and add items to it. Here is an example that adds items to a JavaFX ListView : listView.getItems().add("Item 1"); listView.getItems().add("Item 2"); listView.getItems().add("Item 3"); Adding a ListView to the Scene Graph To make a ListView visible you must add it to the scene graph. This means that you must add the ListView to a Scene object or to some layout component which is then attached to the Scene object. Here is an example showing how to add a JavaFX ListView to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ListView; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class ListViewExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("ListView Experiment 1"); ListView listView = new ListView(); listView.getItems().add("Item 1"); listView.getItems().add("Item 2"); listView.getItems().add("Item 3"); HBox hbox = new HBox(listView); Scene scene = new Scene(hbox, 300, 120); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args);
  • 77. } } The application resulting from running this example would look similar to this screenshot: Notice how the ListView shows multiple options by default. You can set a height and width for a ListView, but you cannot set explicitly how many items should be visible. The height determines that based on the height of each item displayed. If there are more items in the ListView than can fit into its visiible area, the ListView will add scroll bars so the user can scroll up and down over the items. Reading the Selected Value You can read the selected indexes of a ListView via its SelectionModel. Here is an example showing how to read the selected indexes of a JavaFX ListView: ObservableList selectedIndices = listView.getSelectionModel().getSelectedIndices(); The OberservableList will contain Integer objects representing the indexes of the selected items in the ListView. Here is a full JavaFX example with a button added which reads the selected items of the ListView when clicked: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.Button;
  • 78. import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class ListViewExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("ListView Experiment 1"); ListView listView = new ListView(); listView.getItems().add("Item 1"); listView.getItems().add("Item 2"); listView.getItems().add("Item 3"); Button button = new Button("Read Selected Value"); button.setOnAction(event -> { ObservableList selectedIndices = listView.getSelectionModel().getSelectedIndices(); for(Object o : selectedIndices){ System.out.println("o = " + o + " (" + o.getClass() + ")"); } }); VBox vBox = new VBox(listView, button); Scene scene = new Scene(vBox, 300, 120); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } Allowing Multiple Items to be Selected
  • 79. To allow multiple items in the ListView to be selected you need to set the corresponding selection mode on the ListView selection model. Here is an example of setting the selection mode on the JavaFX ListView: listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); Once you have set the SelectionMode.MULTIPLE on the ListView selection model, the user can select multiple items in the ListView by holding down SHIFT or CTRL when selecting additional items after the first selected item. Here is a full JavaFX example that shows how to set a ListView into multiple selection mode, including a button which when clicked will write out the indices of the selected items in the ListView : package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class ListViewExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("ListView Experiment 1"); ListView listView = new ListView(); listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); listView.getItems().add("Item 1"); listView.getItems().add("Item 2"); listView.getItems().add("Item 3"); Button button = new Button("Read Selected Value"); button.setOnAction(event -> {
  • 80. ObservableList selectedIndices = listView.getSelectionModel().getSelectedIndices(); for(Object o : selectedIndices){ System.out.println("o = " + o + " (" + o.getClass() + ")"); } }); VBox vBox = new VBox(listView, button); Scene scene = new Scene(vBox, 300, 120); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } JavaFX TextField A JavaFX TextField control enables users of a JavaFX application to enter text which can then be read by the application. The JavaFX TextField control is represented by the class javafx.scene.control.TextField . Creating a TextField You create a TextField control by creating an instance of the TextField class. Here is a JavaFX TextField instantiation example: TextField textField = new TextField(); Adding a TextField to the Scene Graph
  • 81. For a JavaFX TextField to be visible the TextField object must be added to the scene graph. This means adding it to a Scene object, or as child of a layout which is attached to a Scene object. Here is an example that attaches a JavaFX TextField to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class TextFieldExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("HBox Experiment 1"); TextField textField = new TextField(); HBox hbox = new HBox(textField); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The result of running the above JavaFX TextField example is an application that looks like this:
  • 82. Getting the Text of a TextField You can get the text entered into a TextField using its getText() method which returns a String. Here is a full example that shows a TextField and a Button and which reads the text entered into the TextField when the button is clicked: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class TextFieldExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("HBox Experiment 1"); TextField textField = new TextField(); Button button = new Button("Click to get text"); button.setOnAction(action -> { System.out.println(textField.getText()); }); HBox hbox = new HBox(textField, button); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) {
  • 83. Application.launch(args); } } Setting the Text of a TextField You can set the text of a TextField using its setText() method. This is often useful when you need to set the initial value for at text field that is part of a form. For instance, editing an existing object or record. Here is a simple example of setting the text of a JavaFX TextField: textField.setText("Initial value"); JavaFX PasswordField • Creating a PasswordField • Adding a PasswordField to the Scene Graph • Getting the Text of a PasswordField Jakob Jenkov Last update: 2016-05-19 A JavaFX PasswordField control enables users of a JavaFX application to enter password which can then be read by the application. The PasswordField control does not show the texted entered into it. Instead it shows a circle for each character entered. The JavaFX PasswordField control is represented by the class javafx.scene.control.PasswordField . Creating a PasswordField You create a PasswordField control by creating an instance of the PasswordField class. Here is a JavaFX PasswordField instantiation example: PasswordField passwordField = new PasswordField();
  • 84. Adding a PasswordField to the Scene Graph For a JavaFX PasswordField to be visible the PasswordField object must be added to the scene graph. This means adding it to a Scene object, or as child of a layout which is attached to a Scene object. Here is an example that attaches a JavaFX PasswordField to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.PasswordField; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class PasswordFieldExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("PasswordField Experiment 1"); PasswordField passwordField = new PasswordField(); HBox hbox = new HBox(passwordField); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The result of running the above JavaFX PasswordField example is an application that looks like this:
  • 85. Getting the Text of a PasswordField You can get the text entered into a PasswordField using its getText() method which returns a String. Here is a full example that shows a PasswordField and a Button and which reads the text entered into the PasswordField when the button is clicked: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class PasswordFieldExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("PasswordField Experiment 1"); PasswordField passwordField = new PasswordField(); Button button = new Button("Click to get password"); button.setOnAction(action -> { System.out.println(passwordField.getText()); }); HBox hbox = new HBox(passwordField, button); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) {
  • 86. Application.launch(args); } } JavaFX TextArea JavaFX TextArea control enables users of a JavaFX application to enter text spanning multiple lines, which can then be read by the application. The JavaFX TextArea control is represented by the class javafx.scene.control.TextArea . Creating a TextArea You create a TextArea control by creating an instance of the TextArea class. Here is a JavaFX TextArea instantiation example: TextArea textArea = new TextArea(); Adding a TextArea to the Scene Graph For a JavaFX TextArea to be visible the TextArea object must be added to the scene graph. This means adding it to a Scene object, or as child of a layout which is attached to a Scene object. Here is an example that attaches a JavaFX TextArea to the scene graph: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.TextArea; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class TextAreaExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("TextArea Experiment 1");
  • 87. TextArea textArea = new TextArea(); VBox vbox = new VBox(textArea); Scene scene = new Scene(vbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The result of running the above JavaFX TextArea example is an application that looks like this: Reading the Text of a TextArea You can read the text entered into a TextArea via its getText() method. Here is an example of reading text of a JavaFX TextArea control via its getText() method: String text = textArea.getText(); Here is a full example that shows a TextArea and a Button and which reads the text entered into the TextArea when the button is clicked: package com.jenkov.javafx.controls; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.layout.VBox;
  • 88. import javafx.stage.Stage; public class TextAreaExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("TextArea Experiment 1"); TextArea textArea = new TextArea(); Button button = new Button("Click to get text"); button.setMinWidth(50); button.setOnAction(action -> { System.out.println(textArea.getText()); textArea.setText("Clicked!"); }); VBox vbox = new VBox(textArea, button); Scene scene = new Scene(vbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } Setting the Text of a TextArea You can set the text of a TextArea control via its setText() method. Here is an example of setting the text of a TextArea control via setText() : textArea.setText("New Text"); JavaFX Accordion The JavaFX Accordion control is a container control which can contain several sections internally, each of which can have their content expanded or collapsed.
  • 89. The Accordion control is implemented by the JavaFX class javafx.scene.control.Accordion. The section displayed inside it are made up of JavaFX TitledPane controls. Here is a screenshot of a JavaFX Accordion control: Notice that none of the sections are expanded. You can expand a section by clicking on the little triangle next to the title for each section. Expanding a section will reveal its content. Here is a screenshot of a JavaFX Accordion with a section expanded: JavaFX Accordion Example Here is a full JavaFX Accordion example so you can quickly get an overview of what its usage looks like: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Accordion; import javafx.scene.control.Label; import javafx.scene.control.TitledPane; import javafx.scene.layout.VBox; import javafx.stage.Stage;
  • 90. public class AccordionExample extends Application { public static void main(String[] args) { launch(args); } public void start(Stage primaryStage) { Accordion accordion = new Accordion(); TitledPane pane1 = new TitledPane("Boats" , new Label("Show all boats available")); TitledPane pane2 = new TitledPane("Cars" , new Label("Show all cars available")); TitledPane pane3 = new TitledPane("Planes", new Label("Show all planes available")); accordion.getPanes().add(pane1); accordion.getPanes().add(pane2); accordion.getPanes().add(pane3); VBox vBox = new VBox(accordion); Scene scene = new Scene(vBox); primaryStage.setScene(scene); primaryStage.show(); } } Create an Accordion Before you can use the JavaFX Accordion control you must first instantiate it. You instantiate it simply using the Java new command, like this: Accordion accordion = new Accordion(); Add TitledPane Objects to Accordion Each section displayed inside a JavaFX Accordion is represented by a JavaFX TitledPane. To add sections to the Accordion control, you create on TitledPane per section, and add it to the Accordion. Here is an example of adding TitledPane sections to a JavaFX Accordion:
  • 91. Accordion accordion = new Accordion(); TitledPane pane1 = new TitledPane("Boats" , new Label("Show all boats available")); TitledPane pane2 = new TitledPane("Cars" , new Label("Show all cars available")); TitledPane pane3 = new TitledPane("Planes", new Label("Show all planes available")); accordion.getPanes().add(pane1); accordion.getPanes().add(pane2); accordion.getPanes().add(pane3); Add Accordion to Scene Graph To make a JavaFX Accordion visible, you must add it to the scene graph. Here is an example of adding a JavaFX Accordion to the JavaFX scene graph: Accordion accordion = new Accordion(); VBox vBox = new VBox(accordion); Scene scene = new Scene(vBox); primaryStage.setScene(scene); primaryStage.show(); Text Controls 1. ScrollPane 2. BorderPane 3. StackPane 4. GridPane 5. FlowPane 6. HBox and VBox JavaFX ScrollPane The JavaFX ScrollPane control is a container that has two scrollbars around the component it contains if the component is larger than the visible area of the ScrollPane. The scrollbars enable the user to scroll around the component shown inside the ScrollPane, so different parts of the component can be seen. The
  • 92. JavaFX ScrollPane controls is represented by the JavaFX class javafx.scene.control.ScrollPane. Here is a screenshot of a JavaFX ScrollPane with a JavaFX ImageView inside: Create a ScrollPane To use a JavaFX ScrollPane you must first create a ScrollPane instance. Here is an example of creating a JavaFX ScrollPane instance: ScrollPane scrollPane = new ScrollPane(); Set ScrollPane Content
  • 93. Once you have created a JavaFX ScrollPane instance you can set the content you want it to display via its setContent() method. Here is an example that sets a JavaFX ImageView as content of a JavaFX ScrollPane: ScrollPane scrollPane = new ScrollPane(); String imagePath = "images/aerial-beverage-caffeine-972533.jpg"; ImageView imageView = new ImageView(new Image(new FileInputStream(imagePath))); scrollPane.setContent(imageView); ScrollPane Viewport The visible part of a JavaFX ScrollPane is called the ScrollPane viewport. As you scroll around the content displayed inside the ScrollPane using the scrollbars, the viewport is moved around the content too, making different parts of the content visible. Content With Effects or Transforms If the content (JavaFX control) you want to display inside the JavaFX ScrollPane uses effects or transforms, you must first wrap these controls in a JavaFX Group. Otherwise the content won't be displayed correctly. Pannable ScrollPane By default the user can only navigate around the content displayed in a JavaFX ScrollPane using its scrollbars. However, it is possible to make a JavaFX ScrollPane pannable. A pannable ScrollPane enables the user to navigate its content by holding down the left mouse button and move the mouse around. This will have the same effect as using the scrollbars. However, using panning you can move the content along both X and Y axis simultaneously. This is not possible using the scrollbars, where the user can only operate one scrollbar at a time. To switch a JavaFX ScrollPane into pannable mode you must set its pannableProperty to the value true. Here is an example of switching a JavaFX ScrollPane into pannable mode: scrollPane.pannableProperty().set(true);
  • 94. Fit To Width The JavaFX ScrollPane fitToWidth property can make the ScrollPane fit its content to the width of the ScrollPane viewport. To do so, the fitToWidth property must be set to the value true. This property is ignored if the content node is not resizable. Here is an example of setting the JavaFX ScrollPane fitToWidth property to true: scrollPane.fitToWidthProperty().set(true); Fit To Height The JavaFX ScrollPane fitToHeight property can make the ScrollPane fit its content to the height of the ScrollPane viewport. To do so, the fitToHeight property must be set to the value true. This property is ignored if the content node is not resizable. Here is an example of setting the JavaFX ScrollPane fitToHeight property to true: scrollPane.fitToHeightProperty().set(true); Showing and Hiding Scrollbars via ScrollBar Policies It is possible to specify when the JavaFX ScrollPane is to show the vertical and horizontal scrollbars. You do so via the ScrollPane hbarPolicyProperty and vbarPolicyProperty properties. These properties can be set to one of the ScrollPane.ScrollBarPolicy enum values. You can choose from the values ALWAYS, AS_NEEDED and NEVER. Here is an example of setting the hbarPolicyProperty and vbarPolicyProperty to ScrollBarPolicy.NEVER: scrollPane.hbarPolicyProperty().setValue(ScrollPane.ScrollBarPolicy.NEVER); scrollPane.vbarPolicyProperty().setValue(ScrollPane.ScrollBarPolicy.NEVER); The above example removes the vertical and horizonal scrollbar from the ScrollPane. Without the scrollbars the user cannot use them to scroll around the content of the ScrollPane. However, if the ScrollPane is in pannable mode (see earlier sections in this JavaFX ScrollPane tutorial) the user can still grab the content and scroll around it with the mouse. JavaFX TitledPane
  • 95. The JavaFX TitledPane control is a container control which displays its content inside a a pane (box) which at the top contains a title - hence the name TitledPane. The TitledPane control is implemented by the javafx.scene.control.TitledPane class. In this JavaFX TitledPane tutorial we will look at how to use the TitledPane control. Here is a JavaFX TitledPane screenshot showing how it looks: A TitledPane can be collapsed so only the title bar is visible. This functionality is used inside the JavaFX Accordion control. The TitledPane can of course be expanded too. I will show how that works later in this tutorial. Creating a JavaFX TitledPane In order to use a JavaFX TitledPane you must first create a TitledPane instance. Here is an example of creating a JavaFX TitledPane: Label label = new Label("The content inside the TitledPane"); TitledPane titledPane = new TitledPane("The Title", label); Notice the second line in the code example. This is the line that creates the TitledPane instance. Notice how the title to display in the TitledPane is passed as a parameter to the constructor. Notice also, how the content to display, a JavaFX Node, is also passed as a parameter to the constructor. In this example the content is just a simple JavaFX Label. Adding the TitledPane to the JavaFX Scene Graph
  • 96. To make a JavaFX TitledPane instance visible, it must be added to a JavaFX scene graph. Here is a full example of adding a JavaFX TitledPane to a JavaFX scene graph: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TitledPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class TitledPaneExample extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { Label label = new Label("The content inside the TitledPane"); TitledPane titledPane = new TitledPane("The Title", label); Scene scene = new Scene(new VBox(titledPane)); primaryStage.setScene(scene); primaryStage.show(); } } Collapse and Expand a TitledPane The user can collapse and expand a JavaFX TitledPane using the small triangle next to the title in the title bar of the TitledPane . Here is an example of how a collapsed TitledPane looks: Notice how the content of the TitledPane is no longer visible.
  • 97. It is also possible to collapse and expand a TitledPane programmatically. You do so by calling its setExpanded() method. Here is an example of expanding and collapsing a TitledPane programmatically: titledPane.setExpanded(true); titledPane.setExpanded(false); Disable Collapse It is possible to disable the collapse functionality of a JavaFX TitledPane. You do so by calling its setCollapsible() method, passing a value of false as parameter. Here is how switching off the collapsible functionality of a TitledPane looks: Label label = new Label("The content inside the TitledPane"); TitledPane titledPane = new TitledPane("The Title", label); titledPane.setCollapsible(false); JavaFX Pane The JavaFX Pane class is a layout container which can contain other JavaFX components internally, and lay them out. Actually, the JavaFX Pane class does not actually provide any layout algorithm. The Pane class simply displays the components it contains at the locations the components themselves want to be located. In other words, the Pane class uses the layoutX and layoutY specified by its child components to determine where to display them. The JavaFX Pane class, javafx.scene.layout.Pane, is a subclass of the JavaFX Region class, so it inherits all of the Region class functionality. That includes functionality like borders, padding, background settings etc.
  • 98. Create a JavaFX Pane You create a JavaFX Pane simply via its standard no-arg constructor. Here is an example of creating a JavaFX Pane instance: Pane pane = new Pane(); Add Items to a JavaFX Pane You add items JavaFX Pane by obtaining its list of children via getChildren(), and then add the items to that list. Here is an example of adding a JavaFX Label to a JavaFX Pane: Pane pane = new Pane(); pane.getChildren().add(new Label("Hello Pane")); If you repeat the last line multiple times, you will add multiple Label instances to the Pane. Just keep in mind, that unless you change the layoutX and / or layoutY properties of the added Labels, all the Label instances will be displayed in the same X and Y position - meaning on top of each other. Adding a JavaFX Pane to the Scene Graph Here is an example of adding a JavaFX Pane to the JavaFX scene graph - by setting the Pane as the root node of a JavaFX Scene: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.Pane; import javafx.stage.Stage; public class PaneExample extends Application { public static void main(String[] args) { launch(args); } public void start(Stage primaryStage) { Pane pane = new Pane();
  • 99. pane.getChildren().add(new Label("Hello Pane")); Scene scene = new Scene(pane); primaryStage.setScene(scene); primaryStage.show(); } } JavaFX FlowPane A JavaFX FlowPane is a layout component which lays out its child components either vertically or horizontally, and which can wrap the components onto the next row or column if there is not enough space in one row. The JavaFX FlowPane layout component is represented by the class javafx.scene.layout.FlowPane Creating a FlowPane You create a JavaFX FlowPane via its constructor. Here is a JavaFX FlowPane instantiation example: FlowPane flowpane = new FlowPane(); Adding Children to a FlowPane You can add children to a FlowPane by obtaining its child collection and add adding the components to it you want the FlowPane to layout. Here is an example of adding 3 buttons to a FlowPane: Button button1 = new Button("Button Number 1"); Button button2 = new Button("Button Number 2"); Button button3 = new Button("Button Number 3"); FlowPane flowpane = new FlowPane(); flowpane.getChildren().add(button1); flowpane.getChildren().add(button2);
  • 100. flowpane.getChildren().add(button3); Adding a FlowPane to the Scene Graph To make a FlowPane visible you must add it to the JavaFX scene graph. To do so you must add the FlowPane instance to a Scene object, or add the FlowPane to a layout component which is added to a Scene object. Here is an example of adding a JavaFX FlowPane to the scene graph: package com.jenkov.javafx.layouts; import javafx.application.Application; import javafx.geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.FlowPane; import javafx.stage.Stage; public class FlowPaneExperiments 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 Number 2"); Button button3 = new Button("Button Number 3"); FlowPane flowpane = new FlowPane(); flowpane.getChildren().add(button1); flowpane.getChildren().add(button2); flowpane.getChildren().add(button3); Scene scene = new Scene(flowpane, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } }
  • 101. The application resulting from this application looks like the following screen shots. Notice how the buttons flow down onto the next horizontal line when the window becomes too small to show them all in a single horizontal row. Horizontal and Vertical Spacing You can set the horizontal and vertical spacing between the components shown inside a JavaFX FlowPane using its setHGap() and setVGap() methods. Here is an example that shows how to set the horizontal and vertical gap between components in a FlowPane : flowpane.setHgap(10); flowpane.setVgap(10); When added to the example earlier, the resulting application would look like this: Notice the horizontal and vertical gaps between the buttons now. Orientation
  • 102. By default the components in a FlowPane are layed out horizontally, wrapping onto the next horizontal line when there is no longer space enough inside the FlowPane to show more components horizontally. You can change the flow orientation (direction) of a FlowPane using its setOrientation() method. You can force the components to be layed out in columns from top to bottom, and then change column when there is no more space in the height to show more components. Here is how you do that: flowpane.setOrientation(Orientation.VERTICAL); JavaFX GridPane A JavaFX GridPane is a layout component which lays out its child components in a grid. The size of the cells in the grid depends on the components displayed in the GridPane, but there are some rules. All cells in the same row will have the same height, and all cells in the same column will have the same width. Different rows can have different heights and different columns can have different widths. The JavaFX GridPane is different from the TilePane in that a GridPane allows different size of cells, whereas a TilePane makes all tiles the same size. The number of rows and columns in a GridPane depends on the components added to it. When you add a component to a GridPane you tell in what cell (row, column) the component should be inserted, and how many rows and columns the component should span. The JavaFX GridPane layout component is represented by the class javafx.scene.layout.GridPane Creating a GridPane You create a JavaFX GridPane via its constructor. Here is a JavaFX GridPane instantiation example: GridPane gridPane = new GridPane();
  • 103. Adding Children to a GridPane You can add children to a JavaFX GridPane in several ways. The easiest way is to use the add() of the GridPane. Here is an example of adding 6 buttons to a GridPane: Button button1 = new Button("Button 1"); Button button2 = new Button("Button 2"); Button button3 = new Button("Button 3"); Button button4 = new Button("Button 4"); Button button5 = new Button("Button 5"); Button button6 = new Button("Button 6"); GridPane gridPane = new GridPane(); gridPane.add(button1, 0, 0, 1, 1); gridPane.add(button2, 1, 0, 1, 1); gridPane.add(button3, 2, 0, 1, 1); gridPane.add(button4, 0, 1, 1, 1); gridPane.add(button5, 1, 1, 1, 1); gridPane.add(button6, 2, 1, 1, 1); The first parameter of the add() method is the component (node) to add to the GridPane. The second and third parameter of the add() method is the column index and row index of the cell in which the component should be displayed. Column and row indexes start from 0. The fourth and fifth parameter of the add() method are the oclumn span and row span of the component, meaning how many rows and columns the component should extend to. Column span and row span works similarly to colspan and rowspan in an HTML table. Adding a GridPane to the Scene Graph To make a JavaFX GridPane visible you must add it to the JavaFX scene graph. To do so you must add the GridPane instance to a Scene object, or add the GridPane to a layout component which is added to a Scene object. Here is an example of adding a JavaFX GridPane to the scene graph: package com.jenkov.javafx.layouts;
  • 104. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class GridPaneExperiments extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("GridPane Experiment"); Button button1 = new Button("Button 1"); Button button2 = new Button("Button 2"); Button button3 = new Button("Button 3"); Button button4 = new Button("Button 4"); Button button5 = new Button("Button 5"); Button button6 = new Button("Button 6"); GridPane gridPane = new GridPane(); gridPane.add(button1, 0, 0, 1, 1); gridPane.add(button2, 1, 0, 1, 1); gridPane.add(button3, 2, 0, 1, 1); gridPane.add(button4, 0, 1, 1, 1); gridPane.add(button5, 1, 1, 1, 1); gridPane.add(button6, 2, 1, 1, 1); Scene scene = new Scene(gridPane, 240, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The application resulting from this application looks like the following screen shots.
  • 105. Spanning Multiple Rows and Columns To see how to make a component span multiple columns and rows, look at this modification of the 6 buttons added to the GridPane: gridPane.add(button1, 0, 0, 2, 2); gridPane.add(button2, 2, 0, 1, 1); gridPane.add(button3, 2, 1, 1, 1); gridPane.add(button4, 0, 2, 1, 1); gridPane.add(button5, 1, 2, 1, 1); gridPane.add(button6, 2, 2, 1, 1); Notice how the first button added is given a column span and row span of 2. Notice how the rest of the buttons are added outside of the top left 2 x 2 columns. The layout resulting from these settings looks like this: Horizontal and Vertical Spacing You can set the horizontal and vertical spacing between the components shown inside a JavaFX GridPane using its setHGap() and setVGap() methods. Here is an example that shows how to set the horizontal and vertical gap between components in a GridPane : gridPane.setHgap(10); gridPane.setVgap(10);
  • 106. When added to the example earlier, the resulting application would look like this: Notice the horizontal and vertical gaps between the buttons. If there were no gaps set on the GridPane the buttons would have been positioned next to each other. JavaFX HBox The JavaFX HBox component is a layout component which positions all its child nodes (components) in a horizontal row. The Java HBox component is represented by the class javafx.scene.layout.HBox . Create an HBox You create an HBox using its constructor like this: HBox hbox = new HBox(); HBox also has a constructor which takes a variable length list of components it should layout. Here is an example of how to do that: Button button1 = new Button("Button Number 1"); Button button2 = new Button("Button Number 2"); HBox hbox = new HBox(button1, button2); This HBox example will layout the two Button instances next to each other in a horizontal row. Adding an HBox to the Scene Graph
  • 107. For an HBox to be visible it must be added to the scene graph. This means adding it to a Scene object, or as child of a layout which is attached to a Scene object. Here is an example that attaches a JavaFX HBox with the two Button instances to the scene graph: package com.jenkov.javafx.layouts; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class HBoxExperiments 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 Number 2"); HBox hbox = new HBox(button1, button2); Scene scene = new Scene(hbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The result of running the above JavaFX HBox example is an application that looks like this:
  • 108. Notice that the two Button controls are kept on the same horizontal row even if there is not enough space to show them in their fully preferred widths. The buttons do not "wrap" down on the next line. Child Node Spacing In the earlier example the HBox positioned the nodes (button controls) right next to each other. You can make the HBox insert some space between its nested controls by providing the space in the HBox constructor. Here is an example of setting the space between nested controls in an HBox: HBox hbox = new HBox(20, button1, button2); This example sets the spacing between the controls in the HBox layout component to 20. You can also set the space between the nested controls using the setSpacing() meethod, like this: hbox.setSpacing(50); This example will set the spacing between nested controls to 50. Child Node Margin You can set the margin for child nodes of a JavaFX HBox using the static setMargin() method. Here is an example of setting the margin around a JavaFX Button using the setMargin() method: Button button1 = new Button("Button 1"); HBox hbox = new HBox(button1); HBox.setMargin(button1, new Insets(10, 10, 10, 10)); This example sets the margin around the Button inside the HBox to 10 on each side. Child Node Alignment
  • 109. Since the JavaFX HBox is a container component, meaning it contains other JavaFX components, you can specify how the HBox is to align the components it contains. You do so via the HBox setAlignment() method. Here is an example of setting the alignment of child nodes for a JavaFX HBox: hbox.setAlignment(Pos.BASELINE_CENTER); This example will make the HBox position its child nodes along the baseline (vertically) of the vertical line, and from the center of the line and out (horizontally). The JavaFX VBox control supports the following alignment options: Parameter Vertically Horizontally Pos.BASELINE_LEFT Baseline Left Pos.BASELINE_CENTER Baseline Center Pos.BASELINE_RIGHT Baseline Right Pos.BOTTOM_LEFT Bottom Left Pos.BOTTOM_CENTER Bottom Center Pos.BOTTOM_RIGHT Bottom Right Pos.CENTER_LEFT Center Left Pos.CENTER Center Center Pos.CENTER_RIGHT Center Right Pos.TOP_LEFT Top Left Pos.TOP_CENTER Top Center Pos.TOP_RIGHT Top Right Child Node hgrow You can specify whether a child node of an HBox should grow horizontally to fill any available space available inside the HBox. You do so via the HBox setHgrow() static method. You have to specify which child node the rule is set for. You do so by passing the child node as parameter to setHgrow(). You also have
  • 110. to pass the horizontal expansion policy as parameter to setHgrow(). Here is an example of telling that a child Button to expand horizontally if space is available inside the HBox: Button button1 = new Button("Button 1"); HBox hbox = new HBox(button1); HBox.setHgrow(button1, Priority.ALWAYS); The Priority class contains the following constants you can use to set the expansion policy: 1. Policy.ALWAYS 2. Policy.SOMETIMES 3. Policy.NEVER Please keep in mind that the HBox will only have extra horizontal space available if the HBox is wider than the sum of the preferred widths of its children. HBox Preferred Height The default preferred height of an HBox is set to the same value as the largest preferred height of any of its child nodes. fillHeight The JavaFX HBox fillHeight property can be used to tell the HBox control whether it should expand the height of its children to fill out the whole height of the HBox, or keep its children at their preferred heights. The fillHeight property only affects child components which heights can actually change. For instance, a Button does not change its height by default. It's max height is set to its preferred height. However, you can override that by setting the max height of the Button, or any other component you want to nest inside the HBox, to a value different than its preferred value. Here is an example showing how the fillHeight property works: Button button1 = new Button("Button 1");
  • 111. button1.setMaxHeight(99999.0D); //or Double.MAX_VALUE; HBox hbox = new HBox(button1); hbox.setFillHeight(true); JavaFX VBox The JavaFX VBox component is a layout component which positions all its child nodes (components) in a vertical column - on top of each other. The JavaFX VBox component is represented by the class javafx.scene.layout.VBox . In this JavaFX VBox tutorial I will take a deeper look at the various options the VBox component has for the layout of controls. Create a VBox To use the JavaFX VBox component you must first create an instance of the VBox class. You create a VBox instance using its constructor like this: VBox vbox = new VBox(); VBox also has a constructor which takes a variable length list of components it should layout. Here is an example of how to do that: Button button1 = new Button("Button Number 1"); Button button2 = new Button("Button Number 2"); VBox vbox = new VBox(button1, button2); This VBox example will layout the two Button instances one on top of the other in a vertical column. Adding a VBox to the Scene Graph
  • 112. For a VBox instance to be visible it must be added to the scene graph. This means adding it to a Scene object, or as child of another layout component which is attached to a Scene object. Here is an example that attaches a JavaFX VBox with the two Button instances to the scene graph: package com.jenkov.javafx.layouts; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class VBoxExperiments extends Application{ @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("VBox Experiment 1"); Button button1 = new Button("Button Number 1"); Button button2 = new Button("Button Number 2"); VBox vbox = new VBox(button1, button2); Scene scene = new Scene(vbox, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } } The result of running the above JavaFX VBox example is an application that looks like this:
  • 113. Child Node Spacing In the earlier example the VBox positioned the nodes (button controls) right under the other. You can make the VBox insert some space between its nested controls by providing the space in the VBox constructor. Here is an example of setting the space between nested controls in an VBox: VBox vbox = new VBox(20, button1, button2); This example sets the spacing between the controls in the VBox layout component to 20. You can also set the space between the nested controls using the setSpacing() method, like this: vbox.setSpacing(50); This example will set the spacing between nested controls to 50. Child Node Alignment Since the JavaFX VBox is a container component, meaning it contains other JavaFX components, you can specify how the VBox is to align the components it contains. You do so via the VBox setAlignment() method. Here is an example of setting the alignment of child nodes for a JavaFX VBox: vbox.setAlignment(Pos.BASELINE_CENTER); This example will make the VBox position its child nodes along the baseline (vertically) of the vertical line, and from the center of the line and out (horizontally).
  • 114. The JavaFX VBox control supports the following alignment options: Parameter Vertically Horizontally Pos.BASELINE_LEFT Baseline Left Pos.BASELINE_CENTER Baseline Center Pos.BASELINE_RIGHT Baseline Right Pos.BOTTOM_LEFT Bottom Left Pos.BOTTOM_CENTER Bottom Center Pos.BOTTOM_RIGHT Bottom Right Pos.CENTER_LEFT Center Left Pos.CENTER Center Center Pos.CENTER_RIGHT Center Right Pos.TOP_LEFT Top Left Pos.TOP_CENTER Top Center Pos.TOP_RIGHT Top Right Center Horizontally You can use the child node alignment features to horizontally center the child nodes of a VBox. Here is an example showing how to center the child nodes of a VBox horizontally: vbox.setAlignment(Pos.BASELINE_CENTER); Child Node Margin You can set the margin for child nodes of a JavaFX VBox using the static setMargin() method. Here is an example of setting the margin around a JavaFX Button using the setMargin() method: Button button = new Button("Button 1");
  • 115. VBox vbox = new VBox(button); VBox.setMargin(button, new Insets(10, 10, 10, 10)); This example sets the margin around the Button inside the VBox to 10 on each side. Child Node vgrow You can specify whether a child node of a VBox should grow vertically to fill any available space available inside the VBox. You do so via the VBox setVgrow() static method. You have to specify which child node the rule is set for. You do so by passing the child node as parameter to setVgrow(). You also have to pass the vertical expansion policy as parameter to setVgrow(). Here is an example of telling that a child Button to expand vertically if space is available inside the VBox: Button button = new Button("Button 1"); VBox vbox = new VBox(button); VBox.setVgrow(button, Priority.ALWAYS); The Priority class contains the following constants you can use to set the expansion policy: 1. Policy.ALWAYS 2. Policy.SOMETIMES 3. Policy.NEVER Please keep in mind that the VBox will only have extra vertical space available if the child nodes do not have the same preferred height, or if you explicitly set a preferred height on the VBox that is larger than the preferred height of its child nodes. fillWidth The JavaFX VBox fillWidth property can be used to tell the VBox control whether it should expand the width of its children to fill out the whole width of the VBox, or keep its children at their preferred widths.
  • 116. The fillWidth property only affects child components which widths can actually change. For instance, a Button does not change its width by default. It's max width is set to its preferred width. However, you can override that by setting the max width of the Button, or any other component you want to nest inside the VBox, to a value different than its preferred value. Here is an example showing how the fillWidth property works: Button button = new Button("Button 1"); button.setMaxWidth(99999D); //or Double.MAX_VALUE; VBox vbox = new VBox(button); vbox.setFillWidth(true); VBox CSS Like many other JavaFX controls the VBox component can be styled via CSS. You set the CSS styles of the JavaFX VBox component via its setStyle() method. Styling JavaFX controls via CSS is covered in more detail in the JavaFX CSS Styling tutorial, but I will briefly explain how to style a JavaFX VBox here. Here is an example of setting the CSS styles of a JavaFX VBox component: vbox.setStyle("-fx-padding: 16;"); The VBox component supports the following CSS properties: CSS Property Description -fx-padding Sets the padding between the edge of the VBox and the edge of the outermost child nodes. -fx-border- style Sets the border style of the VBox, in case you want a visible border around it. -fx-border- width Sets the border width. -fx-border- Sets the border insets.
  • 117. insets -fx-border- radius Sets the border radius (of corners). -fx-border- color Sets the border color. VBox FXML You can define a JavaFX VBox from inside a JavaFX FXML document. Here is an example of how a VBox FXML definition looks: <?import javafx.scene.layout.GridPane?> <?import javafx.scene.control.Label?> <?import javafx.scene.layout.VBox?> <GridPane xmlns:fx="http://javafx.com/fxml" fx:controller="sample.Controller" alignment="center" hgap="10" vgap="10"> <VBox> <Label>Text inside VBox</Label> </VBox> </GridPane> Here are some of the most commonly used VBox XML element attributes: • border • alignment • fillWidth MENUS MENU CONTROLS 1. Menu Basics 2. Menu bars 3. MenuItem
  • 118. MENUBAR JavaFX MenuBar The JavaFX MenuBar provides JavaFX applications with a visual drop down menu similar to that most desktop applications have at the top of their application window. The JavaFX MenuBar is represented by the class javafx.scene.control.MenuBar . Here is an example screenshot of what a JavaFX MenuBar can look like: Creating a MenuBar Instance Before you can use the JavaFX MenuBar you must create a MenuBar instance. Here is an example of creating a JavaFX MenuBar instance: MenuBar menuBar = new MenuBar(); Adding a MenuBar to the Scene Graph Before a MenuBar becomes visible you will have to add it to the JavaFX scene graph. Here is an example of adding a JavaFX MenuBar to the scene graph: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar;
  • 119. import javafx.scene.control.MenuItem; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class JavaFXApp extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("JavaFX App"); MenuBar menuBar = new MenuBar(); VBox vBox = new VBox(menuBar); Scene scene = new Scene(vBox, 960, 600); primaryStage.setScene(scene); primaryStage.show(); } } Notice how the MenuBar is added to the root layout (VBox) of the JavaFX scene. This places the MenuBar at the top of the application window. Note that the above example does not add any menus or menu items to the MenuBar, so if you run the example you will not actually see the MenuBar. We will see how to add menus and menu items in the following sections. Creating Menu Instances Once the MenuBar instance is created, you can add Menu instances to it (javafx.scene.control.Menu . A Menu instance represents a single vertical menu with nested menu items. Thus, you can add multiple MenuBar instances to a MenuBar to add multiple vertical drop down menus. Here is an example of adding a Menu to a MenuBar : Menu menu1 = new Menu("Menu 1"); MenuBar menuBar = new MenuBar();
  • 120. menuBar.getMenus().add(menu1); Here is a screenshot showing the JavaFX MenuBar as configured by the example code above: As you can see, there is only a single menu in the MenuBar titled "Menu 1" . This menu has no menu items nested under it. We will see how to add menu items to a Menu in the following sections. Menu Graphics You can set a graphic icon for a Menu by calling its setGraphic() method. The graphic icon will be displayed next to the text label of the menu. Here is an example of setting a graphic icon for a JavaFX Menu instance: Menu menu = new Menu("Menu 1"); menu.setGraphic(new ImageView("file:volleyball.png")); Here is how the resulting menu could look in a JavaFX application: Menu Events
  • 121. A JavaFX Menu instance can fire several events which you can listen for in your application. The most commonly used events are: • onShowing • onShown • onHiding • onHidden When a Menu is clicked with the mouse it shows its contents. This action fires the event onShowing before the Menu starts showing its menu items. Once the menu is fully visible the onShown event is fired. When an shown (open) Menu is clicked with the mouse it hides its contents again. This action fires the event onHiding before the Menu starts hiding its menu items. Once the menu is fully hidden the onHidden event is fired. You can set Menu event listeners for the events above using the methods setOnShowing(), setOnShown(), setOnHiding() and setOnHidden(). Here is an example of setting event listeners for these events on a JavaFX Menu : Menu menu = new Menu("Menu 1"); menu.setOnShowing(e -> { System.out.println("Showing Menu 1"); }); menu.setOnShown (e -> { System.out.println("Shown Menu 1"); }); menu.setOnHiding (e -> { System.out.println("Hiding Menu 1"); }); menu.setOnHidden (e -> { System.out.println("Hidden Menu 1"); }); The Menu event listeners set above only print out a message to the console when the events fired. You could do something more advanced in case you needed to. Adding Menu Items Once you have created a Menu instance you must add one or more MenuItem instances to it. Each MenuItem corresponds to a menu item in the menu it is added to. Here is an example of adding 2 MenuItem instances to a Menu, which is then added to a MenuBar: Menu menu = new Menu("Menu 1"); MenuItem menuItem1 = new MenuItem("Item 1"); MenuItem menuItem2 = new MenuItem("Item 2");
  • 122. menu.getItems().add(menuItem1); menu.getItems().add(menuItem2); MenuBar menuBar = new MenuBar(); menuBar.getMenus().add(menu); Here is what the resulting JavaFX MenuBar would look like, if used in a JavaFX application: MenuItem Graphics You can add an icon to a menu item. You add a graphic icon to a MenuItem by calling its setGraphic() method, passing as parameter the graphic you want to use for the given MenuItem. Here is an example that adds images to the menu items created in the example in the previous section: Menu menu = new Menu("Menu 1"); MenuItem menuItem1 = new MenuItem("Item 1"); menuItem1.setGraphic(new ImageView("file:soccer.png")); MenuItem menuItem2 = new MenuItem("Item 2"); menuItem1.setGraphic(new ImageView("file:basketball.png")); menu.getItems().add(menuItem1); menu.getItems().add(menuItem2); MenuBar menuBar = new MenuBar(); menuBar.getMenus().add(menu); Here is how a JavaFX MenuBar looks with graphic icons added to its menu items:
  • 123. MenuItem Events The MenuBar configurations created in the previous examples do not react if you select any of the menu items. In order to respond to the selection of a MenuItem you must set an event listener on the MenuItem. Here is an example of adding an event listener to a JavaFX MenuItem: MenuItem menuItem1 = new MenuItem("Item 1"); menuItem1.setOnAction(e -> { System.out.println("Menu Item 1 Selected"); }); Notice the Java Lambda added as parameter to the setOnAction() method of the MenuItem . This lambda expression is executed when the menu item is selected. Submenus The JavaFX MenuBar supports multiple layers of menus. A menu nested inside another menu is called a submenu. The Menu class extends the MenuItem class and can therefore be used as a menu item inside another Menu instance. Here is an example that creates a single JavaFX menu with a submenu inside: Menu menu = new Menu("Menu 1"); Menu subMenu = new Menu("Menu 1.1"); MenuItem menuItem11 = new MenuItem("Item 1.1.1"); subMenu.getItems().add(menuItem11); menu.getItems().add(subMenu);
  • 124. MenuItem menuItem1 = new MenuItem("Item 1"); menu.getItems().add(menuItem1); MenuItem menuItem2 = new MenuItem("Item 2"); menu.getItems().add(menuItem2); MenuBar menuBar = new MenuBar(); menuBar.getMenus().add(menu); The JavaFX MenuBar resulting from the above example will look similar to this: Check Menu Items The JavaFX MenuBar supports using check menu items in a menu. A check menu item is a menu item that can be "selected" and remain selected until unselected later. A small check mark is displayed next to the check menu item as long as it remains selected. The check menu item is represented by the CheckMenuItem (javafx.scene.control.CheckMenuItem) class. Here is an example of a JavaFX menu with a CheckMenuItem in: CheckMenuItem checkMenuItem = new CheckMenuItem("Check this!"); menu.getItems().add(checkMenuItem); The Menu instance then need to be added to a MenuBar to be visible, as you have seen in earlier examples. Here is how the resulting menu looks, with the check menu menu item checked:
  • 125. Radio Menu Item The JavaFX MenuBar also supports radio menu items. Radio menu items are menu items of which only one of a set of menu items can be selected - just like standard JavaFX radio buttons. The radio menu item is represented by the RadioMenuItem. The RadioMenuItem instance must be added to a ToggleGroup to make them mutually exclusive. That is how JavaFX knows which RadioMenuItem instance belong together. Here is an example of a JavaFx menu that uses a set of radio menu items: Menu menu = new Menu("Menu 1"); RadioMenuItem choice1Item = new RadioMenuItem("Choice 1"); RadioMenuItem choice2Item = new RadioMenuItem("Choice 2"); RadioMenuItem choice3Item = new RadioMenuItem("Choice 3"); ToggleGroup toggleGroup = new ToggleGroup(); toggleGroup.getToggles().add(choice1Item); toggleGroup.getToggles().add(choice2Item); toggleGroup.getToggles().add(choice3Item); menu.getItems().add(choice1Item); menu.getItems().add(choice2Item); menu.getItems().add(choice3Item); MenuBar menuBar = new MenuBar(); menuBar.getMenus().add(menu); Here is how the JavaFx menu resulting from this example code looks:
  • 126. Menu Item Separators The MenuBar supports menu item separators. A separator is a horizontal line that separates groups of menu items. A separator is often used to signal to users what menu items are related to each other. Menu item separators are represented by the SeparatorMenuItem class. Here is an example of a menu with two menu items separated by a SeparatorMenu: MenuItem item1 = new MenuItem("Item 1"); MenuItem item2 = new MenuItem("Item 2"); SeparatorMenuItem separator = new SeparatorMenuItem(); menu.getItems().add(item1); menu.getItems().add(separator); menu.getItems().add(item2); MenuBar menuBar = new MenuBar(); menuBar.getMenus().add(menu); Here is how the resulting JavaFX menu would look like:
  • 127. Custom Control Menu Items The JavaFX MenuBar also supports using custom JavaFX controls as menu items. To do so you need to use the CustomMenuItem (javafx.scene.control.CustomMenuItem) class. The CustomMenuItem class has a setContent() method which you can use to set the custom JavaFX control to show in the menu. Here is an example that shows both a JavaFX Button and a JavaFX Slider as custom menu items: Menu menu = new Menu("Menu 1"); Slider slider = new Slider(0, 100, 50); CustomMenuItem customMenuItem = new CustomMenuItem(); customMenuItem.setContent(slider); customMenuItem.setHideOnClick(false); menu.getItems().add(customMenuItem); Button button = new Button("Custom Menu Item Button"); CustomMenuItem customMenuItem2 = new CustomMenuItem(); customMenuItem2.setContent(button); customMenuItem2.setHideOnClick(false); menu.getItems().add(customMenuItem2); MenuBar menuBar = new MenuBar(); menuBar.getMenus().add(menu); Notice the call to CustomMenuItem setHideOnClick() with the value false as parameter. This is done to keep the menu open while the user interacts with the custom menu item control. If you set the value to true the menu will close as soon as the user clicks the control the first time, making further interaction impossible. For normal menu items you actually do want the menu to close immediately, but for some custom menu items you may not want that. The menu can still be closed by clicking on the menu title again. Here is how the resulting menu looks:
  • 128. JavaFX ContexMenu The JavaFX ContextMenu component provides a standard right click menu for JavaFX controls. The JavaFX ContextMenu is represented by the class javafx.scene.control.ContextMenu. You create a ContextMenu instance and attach it to the JavaFX control you want the ContextMenu to be active for. Here is a screenshot of a JavaFX TextArea with a ContextMenu attached and shown:
  • 129. Full ContextMenu Example Here is a full JavaFX ContextMenu example to give you a quick overview of how using the ContextMenu looks: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class ContextMenuExample extends Application { public static void main(String[] args) { launch(args); } public void start(Stage primaryStage) { ContextMenu contextMenu = new ContextMenu(); MenuItem menuItem1 = new MenuItem("Choice 1"); MenuItem menuItem2 = new MenuItem("Choice 2"); MenuItem menuItem3 = new MenuItem("Choice 3"); menuItem3.setOnAction((event) -> { System.out.println("Choice 3 clicked!"); }); contextMenu.getItems().addAll(menuItem1,menuItem2,menuItem3); TextArea textArea = new TextArea(); textArea.setContextMenu(contextMenu); VBox vBox = new VBox(textArea); Scene scene = new Scene(vBox); primaryStage.setScene(scene); primaryStage.setTitle("JavaFX App"); primaryStage.show(); } } Create a ContextMenu
  • 130. To use a JavaFX ContextMenu you must first create a ContextMenu instance. Here is an example of creating a JavaFX ContextMenu: ContextMenu contextMenu = new ContextMenu(); Add Menu Items to the ContextMenu The ContextMenu needs one or more MenuItem instances which are displayed in the menu. To detect which menu item was clicked, you add listeners to the MenuItem instances. Here is an example of adding MenuItem instances to a ContextMenu: ContextMenu contextMenu = new ContextMenu(); MenuItem menuItem1 = new MenuItem("Choice 1"); MenuItem menuItem2 = new MenuItem("Choice 2"); MenuItem menuItem3 = new MenuItem("Choice 3"); menuItem3.setOnAction((event) -> { System.out.println("Choice 3 clicked!"); }); contextMenu.getItems().addAll(menuItem1,menuItem2,menuItem3); Notice how there is an onAction listener set on the third MenuItem, using setOnAction(), passing Java Lambda Expression as listener. If this MenuItem is clicked, the action listener is executed. Add ContextMenu to JavaFX Control A JavaFX ContextMenu needs to be attached to a JavaFX control to be active. You add a ContextMenu to a control via the setContextMenu() of a JavaFX control. Here is an example of adding a JavaFX ContextMenu to a JavaFX control: TextArea textArea = new TextArea(); textArea.setContextMenu(contextMenu);
  • 131. MENU CONTROLS 4. Menus 5. Basics 6. Menu 7. Menu bars 8. MenuItem JAVAFX ADDITIONAL FEATURES Charts • JavaFX comes with a set of built-in ready-to-use chart components. • It is not have to code charts from scratch every time you need a basic chart. JavaFX contains the following chart components: • AreaChart • BarChart • BubbleChart • LineChart • PieChart • ScatterChart • StackedAreaChart • StackedBarChart 2D Graphics
  • 132. JavaFX contains features that makes it easy to draw 2D graphics on the screen. 3D Graphics • JavaFX contains features that make it easy to draw 3D graphics on the screen. Audio • JavaFX contains features that make it easy to play audio in JavaFX applications. • This is typically useful in games or educational applications. Video JavaFX contains features that makes it easy to play video in JavaFX applications. This is typically useful in streaming applications, games or educational applications. WebView • JavaFX contains a WebView component which is capable of showing web pages (HTML5, CSS etc.). • The JavaFX WebView component is based on WebKit - the web page rendering engine also used in Chrome and Safari. • The WebView component makes it possible to mix a desktop application with a web application. • There are times where that is useful. • For instance, if you already have a decent web application, but need some features which can only be provided sensibly with a desktop application - like disk access, communication with other network protocols than HTTP (e.g UDP, IAP etc.) .