“There are no shortcuts to any place worth going.”
—Beverly Sills
You have now explored basic Java programming as a console application—text-based applications with no graphics. But on many occasions you might prefer to have graphical user interface (GUI) applications. In Java, you can use the Java Abstract Window Toolkit (AWT), Java Swing, and JavaFX widget toolkits to develop GUI programs. GUI programming has always been Java's Achilles heel, meaning it was cumbersome and had no built-in charting functions. Thanks to the latest version of JavaFX, all this is going to change. Comparing with Java Swing, JavaFX has improved event handling, has special effects, allows skins to be created with Cascading Style Sheets (CSS), has more consistent controls, is easier for animation, and supports modern touchscreen devices. JavaFX claims to be the next-generation client application platform for desktop, mobile, and embedded systems built on Java. In this chapter, I will introduce first Java Swing applications and then JavaFX applications.
Java Swing is a GUI widget toolkit that was developed to provide a more sophisticated set of GUI components than the earlier Java AWT widget toolkit. Example 4.1 shows a standard Java Swing GUI application, named GUIApplication.java
. To create a Java Swing GUI program, you need to extend the JFrame
class, which is in the javax.swing.*
library. You also need to implement the createAndShowGUI()
method, which creates and sets up the window. To display the window, you need to call the createAndShowGUI()
method as a thread in the main()
method. Figure 4.1 shows the output of the SwingApplication1.java
program, which in this case is just a blank window.
Next, you can add some components to the SwingApplication1.java
program, such as a label and a text field, as shown in Example 4.2. The layout of the window is FlowLayout
, which means you add the components to the window from left to right and from top to bottom. You can also add some actions to the text field so that each time the user types something in the text field and hits the Enter key, it is copied to the label. To do this, your code must extend from the JFrame
class, and it also needs to implement ActionListener
and import the javax.swing.*
, javax.awt.*
, and javax.awt.event.*
libraries. Java ActionListener
is a type of event handler that is triggered when an action happens, such as a button being pressed, a check box being ticked, and so on. Figure 4.2 shows the output of the SwingApplication2.java
program.
Example 4.3 shows another Java Swing program with a text field, a button, and a label. It adds an action to the button so that each time you click the button, it calculates the square of the number typed in the text field and displays it in the label. Figure 4.3 shows the output.
When you have a lot of GUI components in your program, you need to use the Java Layout Manager, which is included in the standard Java JDK. The Java Layout Manager supports many layouts, such as FlowLayout
, BorderLayout
, GridLayout
, BoxLayout
, CardLayout
, GridBagLayout
, GroupLayout
, and SpringLayout
. The default is FlowLayout
.
For more information and tutorials on Java Swing, see the following links:
https://docs.oracle.com/javase/tutorial/uiswing/
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
https://docs.oracle.com/javase/8/docs/technotes/guides/swing/index.html
https://www.tutorialspoint.com/swing/
JavaFX is a Java library designed for developing sophisticated Java GUI applications. JavaFX can be used to develop both standard desktop applications and rich Internet applications (RIAs), which are the web applications that provide features and an experience similar to those of desktop applications. Applications built in JavaFX can run on multiple platforms, including web, mobile, and desktops. RIAs do not require any additional software to run. The other two main RIA technologies are Adobe Flash and Microsoft Silverlight.
JavaFX was originally developed by Sun Microsystems, and JavaFX 1.0 was released on December 4, 2008. Since the release of JavaFX 8.0 in March 2014, JavaFX has been an integral part of Java. Oracle will continue to support it until March 2022. The latest version is JavaFX 11.0, released on September 18, 2018. It builds on top of Java 10 or preferably Java 11. It is now released as a stand-alone library and is no longer part of the standard Java SDK. In the future, JavaFX will be supported by the company Gluon as a downloadable module in addition to the JDK.
For more information about the latest JavaFX, its download, and the installation instructions, please visit this site:
https://openjfx.io/openjfx-docs/#introduction
The simplest way to create a JavaFX application is to use a Java IDE, such as IntelliJ IDEA, which comes with the JavaFX plugin enabled by default. Figure 4.4 shows how to create a JavaFX project using IntelliJ IDEA.
A typical JavaFX application will have three major components: stage, scene, and nodes. A stage is a window that contains all the GUI components of a JavaFX application. A stage has two parameters, width
and height
. It is divided as Content Area and Decorations (Title Bar and Borders).
There are five types of stages: Decorated, Undecorated, Transparent, Unified, and Utility.
A scene is a container in which all the components are presented, and the nodes are the GUI components that can be added to the scene. A node can be a 2D or 3D object (circle, rectangle, polygon, and so on), a GUI control (label, button, check box, choice box, text area, and so on), container (layout panes, such as border pane, grid pane, flow pane, and so on), or a media element (such as audio, video, or image).
Example 4.4 shows a simple JavaFX program, which merely creates an empty window program. To create a JavaFX program, your program needs to extend the Application
class, which is part of the javafx.application
package, and you also need to import a range of other JavaFX libraries. You will also need to implement the Start()
method to set up all your GUI components and use the launch()
method to run your program. To run this example, just create a JavaFX project called JavaFXApplication1
using IntelliJ IDEA and copy the following code into the main.java
program (a procedure you'll follow for all of this chapter's JavaFX examples). Figure 4.5 shows the example code in IntelliJ IDEA and the running output window of the program.
Example 4.5 shows an improved version of the previous JavaFX program, with a label and a button. It uses the FlowPane
layout, in which the GUI objects can be added as in the flow layout. An action was also added to the button so that each time you click the button, it displays Hello World!
on the label. To run this example, just create a JavaFX project called JavaFXApplication2
using IntelliJ IDEA and copy the following code into the main.java
program. Figure 4.6 shows the output.
Similar to Java Swing, JavaFX also supports many different layouts, called layout panes, such as FlowPane
, BorderPane
, GridPane
, StackPane
, HBox
, VBox
, TextFlow
, AnchorPane
, TitlePane
, and so on.
For many years, Java offered no built-in charting functions. Thanks to JavaFX, users can now easily create bar charts, pie charts, line charts, scatter charts, and so on, using the built-in JavaFX chart functions. Example 4.6 shows how to create a line chart in JavaFX using the LineChart
, NumberAxis
, and XYChart
classes. To create a chart, you will first need to create NumberAxis
objects for the x- and y-axes. Next, you'll create a LineChart
object with NumberAxis
objects added to it, then create an XYChart.Series
object, and finally add the XY data to it as XYChart.Data
objects. Next, add the XYChart.Series
object to the LineChart
object.
To run this example, just create a JavaFX project called JavaFXApplication3
using IntelliJ IDEA, and copy the following code into the main.java
program. Figure 4.7 shows the output window created by the code.
Handling user logins is a basic function of any GUI application. Example 4.7 shows a JavaFX login example using GUI components such as a label, a text field, and buttons. The GridPane
layout is used, allowing the GUI objects to be added in the grid. To run this example, just create a JavaFX project called JavaFXApplication4
using IntelliJ IDEA, and copy the following code into the main.java
program. Figure 4.8 shows the output from this example.
In JavaFX, you can use the Alert
class to display a pop-out message box to display an error message; here's an example:
new Alert(Alert.AlertType.ERROR, " An error occurred!").showAndWait();
Here's another example:
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText("An error occurred!");
alert.showAndWait();
You can also use the Alert
class to display a standard message box with OK and Cancel buttons, as in this example:
Alert alert = new Alert(Alert.AlertType.WARNING,
"Are you sure to continue? ",
ButtonType.OK,
ButtonType.CANCEL);
alert.setTitle("Warning");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
//do something
}
else{
//do something else
}
A picture is worth a thousand words, especially online, and image viewers have become a common and convenient tool in today's computing environment. Example 4.8 shows a JavaFX image viewer example using the Image
and ImageView
classes. To view an image, first you need to create an Image
object, which can load an image from a file using the FileInputStream
class. The xxxx
indicates the path of the image you want to view, such as C:\bigbang.png
. You also need to throw a FileNotFoundException
. The next step is to create an ImageView
object and add the Image
object to it. To run this example, just create a JavaFX project called JavaFXApplication5
using IntelliJ IDEA and copy the following code into the main.java
program. Figure 4.9 shows the output of the example.
You can also use JavaFX to connect to the Web and view its content. Example 4.9 shows a JavaFX web viewer created using the WebView
class. To run this example, just create a JavaFX project called JavaFXApplication6
using IntelliJ IDEA, and copy the following code into the main.java
program. Figure 4.10 shows the output from the example.
Menus are another common element of GUI applications. Example 4.10 shows a simple JavaFX menu created using the Menu
, MenuBar
, MenuItem
, and SeparatorMenuItem
classes. To create a menu, the program takes the following steps:
MenuBar
object.Menu
object, along with some MenuItem
objects; in this case, there is Open
, Separator
, and Exit
. An action is added to the Exit
object so that when the item is clicked, the program terminates: Platform.exit()
.MenuItem
objects to the Menu
object.Menu
object to the MenuBar
object.BorderPane
layout, and add the MenuBar
object to the north.BorderPane
layout to the scene.Here, for the menu object, setOnAction()
is used to add actions to the object, and Platform.exit()
will terminate the program. For example,
exitMenuItem.setOnAction(actionEvent -> Platform.exit())
will add program termination to the exitMenuItem
object. To run this example, just create a JavaFX project called JavaFXApplication7
using IntelliJ IDEA, and copy the following code into the main.java
program. Figure 4.11 shows the output from the example.
In many applications, you need to read and write files. In JavaFX, you can use the FileChooser
class to open a file chooser dialog where the user can select files for reading and writing. Example 4.11 shows a JavaFX menu application that uses the FileChooser
class. This is an improved version of the previous image viewer example. Instead of loading the same image file, it presents a button that allows the user to select an image file to view. Again, a FileNotFoundException
exception must be thrown or handled using a try…catch
block.
To run this example, just create a JavaFX project called JavaFXApplication8
using IntelliJ IDEA, and copy the following code into the main.java
program. Figure 4.12 shows the output from the example.
There are many good JavaFX tutorials on the Internet. Figure 4.13 shows the official JavaFX tutorial from Oracle (https://docs.oracle.com/javafx/2/get_started/jfxpub-get_started.htm
), which is comprehensive and includes all the JavaFX documentation.
Figure 4.14 shows a JavaFX tutorial from Tutorialspoint (https://www.tutorialspoint.com/javafx/
). This is a well-presented tutorial that covers a lot of JavaFX topics with illustrative examples.
Figure 4.15 shows another JavaFX tutorial, this one from Jenkov Apps (http://tutorials.jenkov.com/javafx/scatterchart.html
). This is an interesting tutorial, packed with different topics and examples of code.
Figure 4.16 shows the JavaFX tutorial from Eclipse (http://wiki.eclipse.org/Efxclipse/Tutorials
). This is mainly focused on how to develop JavaFX applications using the Eclipse IDE.
Figure 4.17 shows the JavaFX official documentation web site from Oracle (https://docs.oracle.com/javafx/2/
). Figure 4.18 shows the corresponding JavaFX API documentation web site from Oracle (https://docs.oracle.com/javafx/2/api/index.html
).
The simplest way to deploy a JavaFX application is as a stand-alone executable JAR file, as described in section 3.13 of the previous chapter. Besides this, JavaFX applications can be deployed to run in a browser, to run on the Web, and as self-contained applications. Java IDEs such as Eclipse and NetBeans all provide JavaFX deployment functions.
Figure 4.19 shows a comprehensive JavaFX deployment guide from Oracle (https://docs.oracle.com/javafx/2/get_started/basic_deployment.htm
). Figure 4.20 shows a JavaFX deployment guide from code.makery (https://code.makery.ch/library/javafx-tutorial/part7/
).
This chapter introduced Java GUI programming. It first introduced Java GUI development using the Java Swing toolkit and then introduced Java GUI development using the latest JavaFX toolkit. It also provided resources including several interesting JavaFX tutorials and information about JavaFX deployment.
Q4.1. | What is the difference between a Java console application and a Java GUI application? |
Q4.2. | What is Java AWT? What is Java Swing? |
Q4.3. | What layouts does Java Swing support? What is the default layout? |
Q4.4. | What is JavaFX? |
Q4.5. | What is the relationship between the stage, scene, and nodes in JavaFX? |
Q4.6. | What types of charts are supported in JavaFX? |
Q4.7. | What layout panes are available in JavaFX? |
Q4.8. | What is the relationship between Menu , MenuBar , and MenuItem ? |