SlideShare a Scribd company logo
1 of 132
Download to read offline
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
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf

More Related Content

What's hot (20)

Cohesion and coupling
Cohesion and couplingCohesion and coupling
Cohesion and coupling
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
state modeling In UML
state modeling In UMLstate modeling In UML
state modeling In UML
 
Unit 4 designing classes
Unit 4  designing classesUnit 4  designing classes
Unit 4 designing classes
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Unit 1 OOSE
Unit 1 OOSE Unit 1 OOSE
Unit 1 OOSE
 
Android ui layout
Android ui layoutAndroid ui layout
Android ui layout
 
Object oriented modeling and design
Object oriented modeling and designObject oriented modeling and design
Object oriented modeling and design
 
Java Notes
Java NotesJava Notes
Java Notes
 
Object Oriented Relationships
Object Oriented RelationshipsObject Oriented Relationships
Object Oriented Relationships
 
State
StateState
State
 
Object Modeling Techniques
Object Modeling TechniquesObject Modeling Techniques
Object Modeling Techniques
 
Oomd unit1
Oomd unit1Oomd unit1
Oomd unit1
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
The Object Model
The Object Model  The Object Model
The Object Model
 
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMINGCS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
 

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

Java AWT and Java FX
Java AWT and Java FXJava AWT and Java FX
Java AWT and Java FXpratikkadam78
 
PROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IIPROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IISivaSankari36
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Javababak danyal
 
Java for android developers
Java for android developersJava for android developers
Java for android developersAly Abdelkareem
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
Programming Java Concept of Event Handling
Programming Java Concept of Event HandlingProgramming Java Concept of Event Handling
Programming Java Concept of Event HandlingJadavsejal
 
MTA understanding java script and coding essentials
MTA understanding java script and coding essentialsMTA understanding java script and coding essentials
MTA understanding java script and coding essentialsDhairya Joshi
 
Mi0041 java and web design
Mi0041   java and web designMi0041   java and web design
Mi0041 java and web designsmumbahelp
 
CIS 406 Entire Course NEW
CIS 406 Entire Course NEWCIS 406 Entire Course NEW
CIS 406 Entire Course NEWshyamuopfive
 
Oracle 10g Forms Lesson 13
Oracle 10g Forms Lesson 13Oracle 10g Forms Lesson 13
Oracle 10g Forms Lesson 13KAMA3
 
Functional UI testing of Adobe Flex RIA
Functional UI testing of Adobe Flex RIAFunctional UI testing of Adobe Flex RIA
Functional UI testing of Adobe Flex RIAViktor Gamov
 
Strayer cis 406 week 6 assignment 1 financial portfolio new
Strayer cis 406 week 6 assignment 1 financial portfolio newStrayer cis 406 week 6 assignment 1 financial portfolio new
Strayer cis 406 week 6 assignment 1 financial portfolio newdixonbakerr
 

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

Java AWT and Java FX
Java AWT and Java FXJava AWT and Java FX
Java AWT and Java FX
 
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
 
PROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IIPROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part II
 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
 
Java for android developers
Java for android developersJava for android developers
Java for android developers
 
Event handling
Event handlingEvent handling
Event handling
 
Event handling
Event handlingEvent handling
Event handling
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
09events
09events09events
09events
 
Programming Java Concept of Event Handling
Programming Java Concept of Event HandlingProgramming Java Concept of Event Handling
Programming Java Concept of Event Handling
 
MTA understanding java script and coding essentials
MTA understanding java script and coding essentialsMTA understanding java script and coding essentials
MTA understanding java script and coding essentials
 
Mi0041 java and web design
Mi0041   java and web designMi0041   java and web design
Mi0041 java and web design
 
Java swing and events
Java swing and eventsJava swing and events
Java swing and events
 
CIS 406 Entire Course NEW
CIS 406 Entire Course NEWCIS 406 Entire Course NEW
CIS 406 Entire Course NEW
 
Les13
Les13Les13
Les13
 
Oracle 10g Forms Lesson 13
Oracle 10g Forms Lesson 13Oracle 10g Forms Lesson 13
Oracle 10g Forms Lesson 13
 
Java FX Part2
Java FX Part2Java FX Part2
Java FX Part2
 
Functional UI testing of Adobe Flex RIA
Functional UI testing of Adobe Flex RIAFunctional UI testing of Adobe Flex RIA
Functional UI testing of Adobe Flex RIA
 
Strayer cis 406 week 6 assignment 1 financial portfolio new
Strayer cis 406 week 6 assignment 1 financial portfolio newStrayer cis 406 week 6 assignment 1 financial portfolio new
Strayer cis 406 week 6 assignment 1 financial portfolio new
 

More from AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING

More from AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING (20)

JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
INTRO TO PROGRAMMING.ppt
INTRO TO PROGRAMMING.pptINTRO TO PROGRAMMING.ppt
INTRO TO PROGRAMMING.ppt
 
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptxCS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
 
CS3391 OOP UT-I T1 OVERVIEW OF OOP
CS3391 OOP UT-I T1 OVERVIEW OF OOPCS3391 OOP UT-I T1 OVERVIEW OF OOP
CS3391 OOP UT-I T1 OVERVIEW OF OOP
 
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptxCS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
 
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
CS3391 -OOP -UNIT – III  NOTES FINAL.pdfCS3391 -OOP -UNIT – III  NOTES FINAL.pdf
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
 
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
CS3391 -OOP -UNIT – II  NOTES FINAL.pdfCS3391 -OOP -UNIT – II  NOTES FINAL.pdf
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
CS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdfCS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdf
 
CS8080 IRT UNIT I NOTES.pdf
CS8080 IRT UNIT I  NOTES.pdfCS8080 IRT UNIT I  NOTES.pdf
CS8080 IRT UNIT I NOTES.pdf
 
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdfCS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
 
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdfCS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
 
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
CS8080_IRT_UNIT - III T13 INVERTED  INDEXES.pdfCS8080_IRT_UNIT - III T13 INVERTED  INDEXES.pdf
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
 
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
CS8080  IRT UNIT - III  SLIDES IN PDF.pdfCS8080  IRT UNIT - III  SLIDES IN PDF.pdf
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
 
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdfCS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
 
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdfCS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
 
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdfCS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
 
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
CS8080_IRT_UNIT - III T10  ACCURACY AND ERROR.pdfCS8080_IRT_UNIT - III T10  ACCURACY AND ERROR.pdf
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
 
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdfCS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
 
CS8080_IRT_UNIT - III T8 FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdf
CS8080_IRT_UNIT - III T8  FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdfCS8080_IRT_UNIT - III T8  FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdf
CS8080_IRT_UNIT - III T8 FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdf
 

Recently uploaded

Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 

Recently uploaded (20)

Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 

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