OOP Lab 12
OOP Lab 12
Statement Purpose:
The objective of this lab is to familiarize the students with graphical user interface development. For this
purpose, JavaFX framework will be introduced to students in this Lab. various concepts relevant to JavaFX
application and its skeleton will be introduced to students. The students will also get hands on experience on
drag-n-drop based software namely Scene Builder, to build JavaFX scene based on FXML language.
Software Resources
• Jave SE 8 or higher, IDE IntelliJ Idea
• JavaFX libraries
Instructor Note:
132 | P a g e
Suggested Prelab Reading
Java’s UI rameworks include Java AWT, Java Swing, and JavaFX. These are all toolkits used to build Graphical
User Interfaces (GUIs) for Java applications. System dependent AWT (Abstract Window Toolkit) is very
primitive original toolkit, system independent Swing is its more powerful extension, and the latest toolkit
JavaFX is the modern replacement of both the earlier toolkits.
JavaFX is the latest Java-based framework offered by Oracle. JavaFX provides a powerful and flexible
framework that simplifies the creation of modern GUIs based applications. The original JavaFX was based on
a scripting language called JavaFX Script. However, it has been discontinued. Since JavaFX 2.0, JavaFX has
been programmed in Java itself and provides a comprehensive API to develop GUI based applications. JavaFX
also supports FXML language to build the view of the application. JavaFX also supports model-view-controller
architecture (MVC).
To use AWT components, import java.awt package. To use Swing components, you have to import
javax.swing package and in order to use JavaFX components, you import javafx.
Note: You also require some import instructions at the start of the code (refer to lecture slides for these
imports). Be careful of the import statements while typing the code as some javafx classes identifiers are
same as in java.awt API, always select the correct version by selecting javafx version). If you observe
some import statements of type java.awt or javax.swing, retype the component type and select the
one that come with javafx from the list proposed by IDE.
a. Pre-requisite
JavaFX builds on top of JDK and is a standalone component. There are 2 different options for developing
JavaFX applications:
• Use the JavaFX SDK (choosing between 17 or 21 LTS, latest release 22, or an early access build).
• Use a build system (e.g. Maven/Gradle) to download the required modules from Maven Central (choosing
as well between the same mentioned versions).
In any case, for both of the above options, it is required to have a recent version of JDK 21, or at least JDK 17.
133 | P a g e
1. Download JavaFX SDK
If you want to use the JavaFX SDK instead of a build tool, download an appropriate JavaFX runtime for your
operating system from the following link and unzip it to a desired location.
https://gluonhq.com/products/javafx/
iii. Move the JavaFX SDK older o …/java/ folder containing Java JDK (It is optional step)
iv. With that, now the JavaFX library path will be C:\Program Files\Java\ javafx-sdk-21.0.1\lib (which
will be used later)
134 | P a g e
In the next step, extend our Java application to an JavaFX application by proceeding through the following
procedures:
135 | P a g e
Lab Tasks:
Task 1: JavaFX Application without FXML based User Interfaces
Create a java package hierarchy labs.lab12.task1. Create a Java class Main in this package and extend
it from Application class to build JavaFX application.
Once you have extended the main class from the Application class, perform the following steps.
• Add following instance variables to your main class outside any method.
Label response;
ToggleGroup tg;
• Add a call to the method launch in the main method of the class as shown below:
public static void main (String[] args) {
launch(args);
}
• Create the start method by using Generate… from the context menu appeared when right clicked
after the main method and Generate… > Overide Methods… then selecting start (stage:
Stage):void under javafx.application.Application.
136 | P a g e
• A skeleton for Override start() method will appear after the main method.
@Override
public void start(Stage stage) throws Exception {
• In start() method, configure the stage and create an instance of FlowPane as given in below:
stage.setTitle("Lab JavaFX");
FlowPane rootNode = new FlowPane (10, 10); //vertical and horizontal gaps of 10
rootNode.setAlignment (Pos.CENTER);
• In start() method, also create a Scene instance from FlowPane instance as shown below:
Scene myScene = new Scene (rootNode, 300, 180);
stage.setScene (myScene);
• In start() method, also create desired labels, buttons, horizontal separator and radio buttons as shown
below (the radio buttons which can be exclusively selected must be part of the same toggle group – i.e.
instance of class ToggleGroup):
Label choose = new Label (" Select your semester");
response = new Label ("No semester mentioned.");
Button btnConfirm = new Button ("Confirm Semester Selection");
RadioButton rbOne = new RadioButton ("One");
RadioButton rbTwo = new RadioButton ("Two");
RadioButton rbThree = new RadioButton ("Three");
tg = new ToggleGroup ();
rbOne.setToggleGroup (tg);
rbTwo.setToggleGroup (tg);
rbThree.setToggleGroup (tg);
rbOne.setSelected (true);
Separator separator = new Separator ();
separator.setPrefWidth (190);
• In start() method, add all GUI components (nodes) to the root node and set the stage to display:
rootNode.getChildren().addAll (choose, rbOne, rbTwo, rbThree,
separator, btnConfirm, response);
stage.show();
137 | P a g e
Build and Run JavaFX application
▪ Go to Files menu → Settings →Appearance & Behavior →Path Variables, Click + sign and enter the name
of variable as PATH_TO_FX and Its value set to JavaFX libraries folder. Here, C:\Program
Files\Java\javafx-sdk-21.0.1\lib. Click OK to confirm and save.
When you click he buon “Confirm Semester Selection” aer selecing semeser “One”, “Two” or
“Three”, it does nothing. Therefore, register the following event listener before adding all nodes to the root
node.
Run the application again. Aer selecing semeser “One”, “Two” or “Three”, click he buon “Confirm
Semester Selection”, o see he response.
Another approach to develop JavaFX is to use FXML language to convey information about UI components.
Again, writing the complete GUI in FXML would be a tedious job. To ease GUI developers, the drag and drop
application – Scene Builder – is available to develop the GUI with ease and in less time.
When you use FXML file in your application, you need at least the following three files to make an interactive
139 | P a g e
application.
• A main class (class with main method) file which represents your application i.e. ClassName.java
where ClassName extends Application class.
• A layout file e.g. MyLayout.fxml which describes the scene graph.
• In case of an interactive application, you need another file caller controller file of the scene graph e.g.
MyLayoutController.java which has access to the controls and other containers in the UI defined
in layout fxml file describing layout details (i.e. MyLayout.fxml).
Create a java package hierarchy labs.lab12.task2. Create a Java class Main in this package and extend
it from Application class to build this JavaFX application. Follow the instructions described in Task 1. Once
you have extended your main class from the Application class, perform the following steps.
}
• In start method, configure the stage and create an instance of FXMLLoader class as given in below
(be careful of the import statements while typing the code as some javafx classes identifiers are same
as in java.awt API, always select the correct version by selecting javafx version)
stage.setTitle("Lab JavaFX from FXML");
FXMLLoader loader = new FXMLLoader(getClass().getResource("MyLayout.fxml"));
Parent rootNode = loader.load();
Scene myScene = new Scene(rootNode);
stage.setScene(myScene); // Set scene on stage
stage.show(); // Display window
140 | P a g e
Creating fxml File from Scene Builder
Scene Builder tool, enables you to create graphical user interfaces (GUIs) with drag and drop techniques. You
can download Scene Builder from:
https://gluonhq.com/products/scene-builder/
Open Scene Builder and drag and drop components to make a design like the following GUI diagram:
To create above scene, proceed through following steps to insert scene nodes:
• Insert Flow Pane container from Containers menu list into the content panel of Scene Builder. Just double
click the Flow Pan, it will automatically insert a Flow Pan box over “Drag Library items here…” box.
• Insert Label control from Controls menu list into the Flow Pan box by double clicking Label. It will
automatically insert a Label component in Flow Pan box near its top left corner. Select the inserted Label
component and set its Text propery o “Select your semester” by selecting a sequential dropdown menu
(Inspector > Properties > Text). Observe the change in component label in Flow Pan.
• Insert three Radio Button controls from Controls menu list into the Flow Pan box one by one by double
clicking Radio Button. Radio Button components will be placed automatically within Flow Pane next to
each oher and aer he label “Selec your semeser”. Select the Radio Button components one by one
and set their Text propery o “One”, “Two” and “Three”, respecively by following the similar steps as
that for the Label conrol “Select your semester”.
• Double click Separator (Horizontal) control from Controls menu list to insert it into the Flow Pan box.
141 | P a g e
• Double click Button control from Controls menu list to insert it into the Flow Pan. Button component will
be placed automatically within FlowPane. Select Button component and set its Text propery o “Confirm
Semester Selection” by following the similar steps as that for the Label conrol “Select your semester”.
• Similarly, insert another Label control from Controls menu list into the Flow Pan. Select the Label
component and set its Text propery o “No semester mentioned”.
Configure other properties of the scene nodes for better aesthetics as described below:
• Select the Flow Pane component (outer box) and configure the following properties by selecting
sequential dropdown menus Inspector > Layout and Inspector > Properties respectively.
• Select the Separator component and configure its following Layout property by selecting sequential
dropdown menu Inspector > Layout. Separator component will be readjusted automatically within
FlowPane.
Inspector – Layout Value
Pref Width 190
In the menu bar of the Scene Builder, click Preview → Show Preview in Window
This will show, how your scene will look like in real window when executed through JavaFX application.
Proceed through following steps to create the skeleton of the Controller class for the fxml file (i.e.
MyLayout.fxml) so that nodes within scene created through the fxml can be modified when desired.
• Set Controller class name as “MyLayoutController” in Scene Builder by adding name of the
Controller class by selecting sequential dropdown menus Document > Controller on the bottom left
side of the Content panel.
Note: As you are working for this lab task in the package, labs.lab12.task2, you would need to add
142 | P a g e
the fully-qualified path for the Controller class name as “labs.lab12.task2.
MyLayoutController”.
• In the menu bar of the Scene Builder, click View → Show Sample Controller Skeleton. This will show
Controller class for the JavaFX application.
• Add identifiers to all those scene nodes whom you want to modify when application is running (e.g. on
certain actions or events). The identifiers (for objects) can be added in the fx:id attribute in the Inspector
– Code panel of a certain scene node. Select following scene nodes one by one and set fx:id values given
below by selecting sequential dropdown menu Inspector > Code:
By now, the Controller class should look as follows when you click View →Show Sample Controller
Skeleton:
package labs.lab12.task2;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
public class MyLayoutController {
@FXML
private Button btnConfirm;
@FXML
private Label response;
}
• Until now, you can select multiple Radio Buttons simultaneously. Assign same toggle group to each radio
button to select only one out of three at a time. Select each Radio Button one by one and set following
property on it by selecting sequential dropdown menu Inspector > Properties:
Also check (tick/ mark) Radio Button “One” as Selected in Inspector – Properties – Specific.
143 | P a g e
By now, the Controller class should look as follows when you click View → Show Sample Controller
Skeleton:
package labs.lab12.task2;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleGroup;
• Until now, the Button wih ex “Confirm Semester Selection” is doing nohing when you click
it. Select the button and add the following event handler method to on Action event (i.e. click event) by
setting the value in Inspector – Properties – Main property.
Inspector – Code – Main Value
On Action onClickHandler
• Click the View → Show Sample Controller Skeleton to see updated controller class. It should now include
method
void onClickHandler(ActionEvent event) { }
• On the sample skeleton window of Controller class, click on he buon “Save as…”. Selec pah o save
the file in the same package of your current task (i.,e., labs.lab12.task2). Name the file as
“MyLayoutController.java” and save i.
• On Scene Bulder, select File menu, click Save As.... Save the generated fxml file with by naming it
as “MyLayout.fxml” in he same package of your current task (i.,e., labs.lab12.task2).
144 | P a g e
Updating Controller Class in IntelliJ IDEA
In this step, handler functions in the Controller class MyLaoutController will be defined so that they can
perform some operations.
@FXML
void onClickHandler(ActionEvent event) {
RadioButton rb = (RadioButton) tg.getSelectedToggle();
response.setText(rb.getText() + " is confirmed.");
}
IntelliJ IDEA allows you to open .fxml files in JavaFX Scene Builder right from the IDE after you specify
the path to the Scene Builder application in IntelliJ IDEA settings. For integration of Scene Builder with IntelliJ
IDEA, follow the instructions on the following link.
https://www.jetbrains.com/help/idea/opening-fxml-files-in-javafx-scene-builder.html
145 | P a g e
146 | P a g e