JavaFX GUI: Key Concepts and Components
Chapter Objectives
This chapter continues with JavaFX GUIs using Scene Builder covering multiple advanced functionalities and controls. The objectives are as follows:
Continue building JavaFX GUIs with Scene Builder: This includes creating and modifying interfaces using the graphical environment.
Use Pane, BorderPane, TitledPane for advanced layout: Learn how to utilize different pane types to achieve complex layouts.
Create and manage RadioButtons and ListViews: Implementation, management, and customization of these user interface components.
Handle mouse events: Understanding mouse events and their handling in JavaFX applications.
Utilize property binding and listeners: Gain insights into JavaFX's property binding and how listeners can respond to property changes.
Create layouts and controls programmatically: Learn to code the user interface components directly instead of using Scene Builder.
Customize ListView with a custom cell factory: Modifications of ListView behavior and appearance with custom cell presentations.
Display Rectangles and Circles in the scene graph: Learn to draw shapes and display them in your JavaFX application.
13.8 Key JavaFX Modules
JavaFX includes several key modules that facilitate various functionalities:
javafx.base: Contains core APIs essential for all JavaFX applications.
javafx.controls: Provides user interface controls, layouts, and graphical charts.
javafx.fxml: Supplies functionalities for working with FXML files for UI design.
javafx.graphics: Contains classes necessary for graphics, animations, and CSS styling.
javafx.media: Allows for the integration of audio and video content in applications.
javafx.swing: Integration with the Swing libraries for legacy applications.
javafx.web: Enables support for web content within JavaFX applications.
The three most critical modules for every JavaFX application are always added to the build path, as they are required:
javafx.controlsjavafx.fxmljavafx.graphics
Why Add JavaFX to Build Path?
Adding JavaFX libraries is essential for several reasons:
Required for compilation since JavaFX is not included in the default JDK.
Essential for resolving the
javafx.*packages during the build process to eliminate compile-time errors.The absence of JavaFX in the build path leads to errors such as
package javafx... does not exist, hindering project compilation.
Why VM Arguments for JavaFX?
VM Arguments are necessary for execution at runtime:
The Java Virtual Machine (JVM) needs to be informed about the location and modules of JavaFX, which can be specified as follows:
---module-path <path>: Indicates where JavaFX modules are located.
---add-modules javafx.controls, javafx.fxml, javafx.media: Specifies which modules to load during execution.
- Without these VM arguments, while the code compiles successfully, runtime failures will occur indicating that the JavaFX runtime components are missing.
13.2 Node Layout in Scene Graphs
In JavaFX, layout panes manage the size and position of nodes within the scene graph effectively:
Avoid fixed node sizes: Fixed sizes do not adapt well when resizing or if content changes, leading to usability issues.
Relative positioning is key: Nodes are positioned relative to their parent or other nodes, allowing for dynamic layouts.
Layout panes utilize relative positioning: This entails that child node sizes and positions automatically adjust according to their minimum, preferred, and maximum properties defined.
Node Size Properties in JavaFX
JavaFX nodes are characterized by various size properties:
Width and Height: Actual sizes of the node.
Pref Width and Pref Height: Preferred sizes suggested for layout consideration.
Min Width and Min Height: Minimum allowable sizes defined in points.
Max Width and Max Height: Maximum allowable sizes defined in points.
These properties control how a node reacts to layout changes and affect how they are rendered visually in the GUI.
JavaFX Layout Panes
Multiple layout panes are covered, notably:
Pane
BorderPane
GridPane
VBox
Creating a Simple Painter App
This section describes the steps to create a basic Painter application that allows for drawing with the mouse:
Overview of required technologies: Understanding key components such as RadioButtons, mouse event management, and shape handling in JavaFX.
Introduction of RadioButtons and Mouse Events: Motion detection and shape rendering within the GUI using user interactions.
Project setup and GUI design: Using Scene Builder along with programmable components such as the Painter and PainterController classes.
Technologies Overview – Painter App
The key technologies used include but are not limited to:
RadioButtons and ToggleGroup: For mutually exclusive selections.
JavaFX 2D/3D Shapes: Implementing shapes like circles in the app interface.
Layout containers: Including BorderPane, Pane, and TitledPane, aiding in organizing controls.
Mouse event handling methods: Framework to detect and respond to user mouse actions.
RadioButtons and ToggleGroups
RadioButtons allow for a singular choice selection among multiple options, achieved through ToggleGroups that manage selections:
Option 1: Utilize FXML through Scene Builder to assign RadioButtons to a ToggleGroup.
Option 2: Implement in Java code by creating a ToggleGroup object and assigning it to respective RadioButtons using
radioButton.setToggleGroup(group).
Shapes in JavaFX
The package javafx.scene.shape consists of classes meant for displaying various shapes in the scene graph. This project will programmatically create Circle objects in response to user interactions, subsequently attaching them to the drawing area specified in the application.
Layout Panes Used in Painter App
The Painter application employs several types of layout containers:
BorderPane
Pane
VBox
TitledPane
BorderPane Layout Container
The BorderPane is a flexible layout that arranges components in five distinct regions:
Top and Bottom: Span full width of the container.
Left, Center, and Right: Fill vertical space effectively, capable of containing controls or additional layout containers.
Pane Layout Container
This layout allows for absolute positioning, which is leveraged in the Painter app to assign Circle positions based on specified x and y coordinates from the top left corner of the pane.
TitledPane Layout Container
A TitledPane displays a title at the top and can contain collapsible layout nodes, useful for organizing controls like RadioButtons into groups for clarity.
Mouse Event Handling
JavaFX nodes are designed to support a variety of mouse events which include typical interactions like clicks, drags, and hover actions:
Input events: Extend beyond mouse actions; they include keyboard and touchscreen events.
For a complete list of JavaFX node events, refer to the Node class properties prefixed with “on” as listed in the JavaFX documentation.
Mouse Interaction in Painter App
In the Painter Application, drawing occurs during mouse dragging actions:
An event handler is configured to process
onMouseDraggedfor the Pane, allowing Circle objects to be drawn in real time using selected colors and pen sizes at the current mouse location.
Setting a JavaFX Control’s User Data
User data allows for association of specific Object instances to controls, which can be beneficial in event handling:
Method:
setUserData(Object)enables developers to attach metadata, such as color for Drawing Color RadioButtons or Pen size enumerations for Pen Size RadioButtons, which can be referenced later when managing events.
Building Painter App GUI
The subsequent steps guide through building the Painter app's GUI using Scene Builder:
Create a project folder for example files.
Open Scene Builder and create or load
Painter.fxml.Follow detailed steps from adding layouts and controls to configuring their properties according to the specified guidelines.
Adding and Configuring the BorderPane
Steps include:
Drag a BorderPane from Library → Containers to the content panel.
Configure BorderPane: Setting preferred width, height, and insets from stage edges as padding.
Adding VBox and Pane
Drag VBox and Pane into the respective areas of the border pane, adjusting their properties for desired layout behavior.
Customizing TitledPanes and Adding RadioButtons
Each TitledPane should hold multiple RadioButtons organized within a VBox for clarity and proper user interaction management. Settings for margins and spacing are crucial for visual appeal.
Check the Selected property for initial choices to ensure default selections appear upon launch.
Assigning ToggleGroups
Appropriately assign RadioButtons to their respective ToggleGroups to guarantee that only one option is selected in each category
From this point forward, further steps include configuring control events, enhancing controller functionalities, and ensuring a seamless interaction within the UI, leveraging property bindings, binding listeners, and defining a robust controller for efficient management of user interactions.
Summary of PainterApp Architecture and Functionality
This encapsulation not only renders drawing interactions intuitive but also demonstrates the power of JavaFX in creating modern graphical user interfaces. The project showcases essential principles of object-oriented programming encapsulated via effective class and event management strategies, thereby aiding developers in understanding JavaFX's versatile applicability.
13.4 Color Chooser App
Purpose
The Color Chooser Application is designed to illustrate JavaFX property bindings and listeners in action:
Employs the RGBA color system to manage color intensities and opacities through sliders.
Utilizes property binding to keep the UI elements in sync with values adjusted by the user on the sliders.
RGBA Colors
The RGBA model assigns color values through four components:
Red, Green, Blue: Ranges from 0 to 255 (0 = none; 255 = full intensity).
Alpha: Ranges from 0.0 to 1.0 (0.0 = transparent; 1.0 = opaque).
Properties of a Class
JavaFX heavily employs properties, defined via getter and setter methods:
Example:
```java
public final void setPropertyName(Type value) {
// implementation
}public final Type getPropertyName() {
// implementation
}
```
This format associates public properties with private variables.
Property Bindings vs. Listening
JavaFX handles property changes via two major mechanisms:
Property Bindings: Automatically link two properties, allowing changes in one to reflect in the other.
Property Listeners: Respond to property changes through event handlers, enabling dynamic content updates in the UI based on user interaction.
Building Color Chooser GUI
Assembling the Color Chooser's GUI involves constructing the layout in Scene Builder:
Create an FXML file labeled
ColorChooser.fxml.Add necessary UI components such as sliders and text fields.
Bind events and properties logically to ensure that user interactions yield immediate visual updates in the application.
Controller Setup
The controller class named ColorChooserController should handle all the event and property management, facilitating the interaction between the GUI and the application logic.
Implement instance variables and define the necessary binding logic within the
initializemethod to support real-time color updates in the interface.
Final Elements of Color Chooser Functionality
The Color Chooser app effectively showcases not only basic JavaFX functionalities but also the power of responsive design, allowing for real-time feedback and a seamless user experience. Overall, it demonstrates practical applications of modern programming paradigms within JavaFX's robust and rich framework.