Business Applications Programming: Graphical User Interface
Business Applications Programming: Graphical User Interface
Programming
Graphical User Interface
Introduction
• There are current three sets of Java APIs for
graphics programming:
– AWT (Abstract Windowing Toolkit),
– Swing and
– JavaFX.
Introduction
• AWT API was introduced in JDK 1.0. Most of the
AWT components have become obsolete and should
be replaced by newer Swing components.
• Swing API, a much more comprehensive set of
graphics libraries that enhances the AWT, was
introduced as part of Java Foundation Classes (JFC)
after the release of JDK 1.1. JFC consists of Swing,
Java2D, Accessibility, Internationalization, and
Pluggable Look-and-Feel Support APIs. JFC has been
integrated into core Java since JDK 1.2.
• The latest JavaFX, which was integrated into JDK 8,
is meant to replace Swing.
Introduction
• Other than AWT/Swing/JavaFX graphics APIs
provided in JDK, other organizations/vendors
have also provided graphics APIs that work with
Java, such as:
– Eclipse's Standard Widget Toolkit (SWT) (used in
Eclipse),
– Google Web Toolkit (GWT) (used in Android),
– 3D Graphics API such as Java bindings for OpenGL
(JOGL) and Java3D.
Swing
• Introduction
• Features
• Using Swing
• Swing Program Template
• Using Visual GUI Builder – NetBeans
Swing - Introduction
• Swing is part of the so-called "Java Foundation
Classes (JFC)”, which was introduced in 1997
after the release of JDK 1.1.
• JFC was subsequently included as an integral part
of JDK since JDK 1.2.
• JFC consists of:
– Swing API: for advanced graphical programming.
– Accessibility API: provides assistive technology for the
disabled.
– Java 2D API: for high quality 2D graphics and images.
– Pluggable look and feel supports.
– Drag-and-drop support between Java and native
applications.
Swing - Introduction
• The goal of Java GUI programming is to allow the
programmer to build GUI that look good on ALL
platforms.
• JDK 1.0's AWT was awkward and non-object-oriented.
• JDK 1.1's AWT introduced event-delegation (event-
driven) model, much clearer and object-oriented. JDK
1.1 also introduced inner class and JavaBeans – a
component programming model for visual programming
environment (similar to Visual Basic).
• Swing appeared after JDK 1.1. It was introduced into
JDK 1.1 as part of an add-on JFC (Java Foundation
Classes). Swing is a rich set of easy-to-use, easy-to-
understand JavaBean GUI components that can be
dragged and dropped as "GUI builders" in visual
programming environment. Swing is now an integral
part of Java since JDK 1.2.
Swing's Features
• Swing is huge (consists of 18 packages of
737 classes as of JDK 1.8) and has great
depth.
• Compared with AWT, Swing provides a
huge and comprehensive collection of
reusable GUI components, as shown in the
Figure (see next slide)
Swing's Features
Swing's Features
• The main features of Swing are (extracted from the
Swing website):
– Swing is written in pure Java (except a few classes) and
therefore is 100% portable.
– Swing components are lightweight. The AWT components
are heavyweight (in terms of system resource utilization).
– Each AWT component has its own opaque native display,
and always displays on top of the lightweight components.
– AWT components rely heavily on the underlying windowing
subsystem of the native operating system. For example, an
AWT button ties to an actual button in the underlying native
windowing subsystem, and relies on the native windowing
subsystem for their rendering and processing.
– Swing components (JComponents) are written in Java. They
are generally not "weighed-down" by complex GUI
considerations imposed by the underlying windowing
subsystem.
Swing's Features
• The main features of Swing are (extracted
from the Swing website)(cont’d):
– Swing components support pluggable look-
and-feel.
– You can choose between Java look-and-feel
and the look-and-feel of the underlying OS
(e.g., Windows, UNIX or Mac).
• If the later is chosen, a Swing button runs on the
Windows looks like a Windows' button and feels
like a Window's button.
• Similarly, a Swing button runs on the UNIX looks
like a UNIX's button and feels like a UNIX's button.
Swing's Features
• The main features of Swing are (extracted
from the Swing website)(cont’d):
– Swing supports mouse-less operation, i.e., it
can operate entirely using a keyboard.
– Swing components support "tool-tips".
– Swing components are JavaBeans – a
Component-based Model used in Visual
Programming (like Visual Basic).
• You can drag-and-drop a Swing component into a
"design form" using a "GUI builder" and double-
click to attach an event handler.
Swing's Features
• The main features of Swing are (extracted
from the Swing website)(cont’d):
– Swing applications use AWT event-handling
classes (in package java.awt.event). Swing
added some new classes in package
javax.swing.event, but they are not frequently
used.
– Swing applications use AWT's layout manager
(such as FlowLayout and BorderLayout in
package java.awt). It added new layout
managers, such as Springs, Struts, and
BoxLayout (in package javax.swing).
Swing's Features
• The main features of Swing are (extracted
from the Swing website)(cont’d):
– Swing implements double-buffering and
automatic repaint batching for smoother screen
repaint.
– Swing introduced JLayeredPane and
JInternalFrame for creating Multiple
Document Interface (MDI) applications.
– Swing supports floating toolbars (in JToolBar),
splitter control, "undo".
– Others - check the Swing website.
Using Swing API
• We look at:
– Swing's Components
– Swing's Top-Level and Secondary Containers
– The Content-Pane of Swing's Top-Level
Container
– Event-Handling in Swing
– Writing Swing Applications
Swing’s Components
• Compared with the AWT component
classes (in package java.awt), Swing
component classes (in package
javax.swing) begin with a prefix "J",
e.g.:
– JButton,
– JTextField,
– JLabel,
– JPanel,
– JFrame, or JApplet.
Swing’s Components
Swing’s Components
• The figure in the previous slide shows the
class hierarchy of the swing GUI classes.
• There are two groups of classes: containers
and components.
• A container is used to hold components. A
container can also hold containers because it
is a (subclass of) component.
• As a rule, do not mix heavyweight AWT
components and lightweight Swing
components in the same program, as the
heavyweight components will always be
painted on top of the lightweight components.
Swing's Top-Level and
Secondary Containers
Swing's Top-Level and
Secondary Containers
• A Swing application requires a top-level
container.
• There are three top-level containers in Swing:
– JFrame: used for the application's main window (with
an icon, a title, minimize/maximize/close buttons, an
optional menu-bar, and a content-pane), as illustrated.
– JDialog: used for secondary pop-up window (with a
title, a close button, and a content-pane).
– JApplet: used for the applet's display-area (content-
pane) inside a browser’s window.
• There are also secondary containers (such as
JPanel) which can be used to group and
layout relevant components.
The Content-Pane of Swing's
Top-Level Container
• The JComponents are not added onto
the top-level container (e.g., JFrame,
JApplet) directly because they are
lightweight components.
• The JComponents must be added onto
the so-called content-pane of the top-
level container.
• Content-pane is in fact a
java.awt.Container that can be used to
group and layout components.
The Content-Pane of Swing's
Top-Level Container
• There are two ways in which to use the
Content-Pane namely:
– get the content-pane via getContentPane()
from a top-level container, and add components
onto it.
– set the content-pane to a JPanel (the main panel
created in your application which holds all your
GUI components) via JFrame's
setContentPane().
The Content-Pane of Swing's
Top-Level Container
• Example for get the content-pane via
getContentPane() from a top-level container:
public class SwingDemo extends JFrame {
// Constructor
public SwingDemo() {
// Get the content-pane of this JFrame, which is a java.awt.Container
// All operations, such as setLayout() and add() operate on the content-
pane
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Hello, world!"));
cp.add(new JButton("Button"));
...... }
.......
}
The Content-Pane of Swing's
Top-Level Container
• Example with set the content-pane to a Jpanel
via JFrame's setContentPane():
public class SwingDemo extends JFrame {
// Constructor
public SwingDemo() {
// The "main" JPanel holds all the GUI components
JPanel mainPanel = new JPanel(new FlowLayout());
mainPanel.add(new JLabel("Hello, world!"));
mainPanel.add(new JButton("Button"));
// Set the content-pane of this JFrame to the main Jpanel
setContentPane(mainPanel); ......
}
.......
}
The Content-Pane of Swing's
Top-Level Container
• NOTE:
– If a component is added directly into a JFrame,
it is added into the content-pane of JFrame
instead, i.e.,
// Suppose that "this" is a JFrame
add(new JLabel("add to JFrame directly"));
// is executed as
getContentPane().add(new JLabel("add to JFrame
directly"));
Event-Handling in Swing
• Swing uses the AWT event-handling
classes (in package java.awt.event).
• Swing introduced a few new event-
handling classes (in package
javax.swing.event) but they are not
frequently used.
Writing Swing Applications
• In summary, to write a Swing application, you
have:
– Use the Swing components with prefix "J" in package
javax.swing, e.g., JFrame, JButton, JTextField, JLabel, etc.
– A top-level container (typically JFrame) is needed. The
JComponents should not be added directly onto the top-level
container. They shall be added onto the content-pane of the
top-level container. You can retrieve a reference to the
content-pane by invoking method getContentPane() from
the top-level container.
– Swing applications uses AWT event-handling classes, e.g.,
ActionEvent/ActionListener, MouseEvent/MouseListener,
etc.
– Run the constructor in the Event Dispatcher Thread (instead
of Main thread) for thread safety, as shown in the program
template. Below in the Notes section
Writing Swing Applications
• Example to explain the template.
– Swing Example 1: SwingCounter
– see online class for the code
Writing Swing Applications -
Explanation
• JFrame's Content-Pane
– The JFrame's method getContentPane() returns the
content-pane (which is a java.awt.Containter) of the
JFrame.
– You can then set its layout (the default layout is
BorderLayout), and add components into it. For
example:
Container cp = getContentPane(); // Get the content-pane of this
JFrame
cp.setLayout(new FlowLayout()); // content-pane sets to
FlowLayout
cp.add(new JLabel("Counter")); // content-pane adds a JLabel
component ......
cp.add(tfCount); // content-pane adds a JTextField component
......
cp.add(btnCount); // content-pane adds a JButton component
Writing Swing Applications -
Explanation
• JFrame's Content-Pane
– You can also use the JFrame's setContentPane()
method to directly set the content-pane to a JPanel
(or a JComponent). For example:
JPanel displayPanel = new JPanel();
setContentPane(displayPanel);
// "this" JFrame sets its content-pane to a JPanel directly .
....
// The above is different from:
getContentPane().add(displayPanel);
// Add a JPanel into the content-pane. Appearance depends on the
JFrame's layout.
Writing Swing Applications -
Explanation
• JFrame's setDefaultCloseOperation()
– Instead of writing a WindowEvent listener with a
windowClosing() handler to process the "close-
window" button, JFrame provides a method called
setDefaultCloseOperation() to set the default
operation when the user initiates a "close" on this
frame.
– Typically, we choose the option
JFrame.EXIT_ON_CLOSE, which terminates the
application via a System.exit().
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Writing Swing Applications -
Explanation
• Running the GUI Construction Codes on the
Event-Dispatching Thread
– We can invoke the constructor directly in the entry
main() method to setup the GUI components. For
example:
// The entry main method
public static void main(String[] args) {
// Invoke the constructor (by allocating an instance) to setup the GUI
new SwingCounter();
}
– The constructor will be executed in the so-called "Main-
Program" thread. This may cause multi-threading issues
(such as unresponsive user-interface and deadlock).
Writing Swing Applications -
Explanation
• Running the GUI Construction Codes on the
Event-Dispatching Thread
– It is recommended to execute the GUI setup codes in the
so-called "Event-Dispatching" thread, instead of "Main-
Program" thread, for thread-safe operations.
– Event-dispatching thread, which processes events, should
be used when the code updates the GUI.
– To run the constructor on the event-dispatching thread,
invoke static method SwingUtilities.invokeLater() to
asynchronously queue the constructor on the event-
dispatching thread. The code will be run after all pending
events have been processed. For example (see next slide)
Writing Swing Applications -
Explanation
• Running the GUI Construction Codes on the
Event-Dispatching Thread
public static void main(String[] args) {
// Run the GUI codes in the Event-dispatching thread for
thread-safety
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SwingCounter(); // Let the constructor do the
job
}
});
}
Writing Swing Applications -
Explanation
• Running the GUI Construction Codes on the
Event-Dispatching Thread
– Note:
• javax.swing.SwingUtilities.invokeLater() is a cover for
java.awt.EventQueue.invokeLater() (which is used in the
NetBeans' Visual GUI Builder).
• At times, for example in game programming, the
constructor or the main() may contains non-GUI codes.
Hence, it is a common practice to create a dedicated
method called initComponents() (used in NetBeans visual
GUI builder) or createAndShowGUI() to handle all the
GUI codes (and another method called initGame() to
handle initialization of the game's objects). This GUI init
method shall be run in the event-dispatching thread.
Swing Example 2: SwingAccumulator
• See file SwingAccumulator.java on the online
class.
Writing Swing Applications -
Explanation
• Running the GUI Construction Codes on the
Event-Dispatching Thread
– Note:
• javax.swing.SwingUtilities.invokeLater() is a cover for
java.awt.EventQueue.invokeLater() (which is used in the
NetBeans' Visual GUI Builder).
• At times, for example in game programming, the
constructor or the main() may contains non-GUI codes.
Hence, it is a common practice to create a dedicated
method called initComponents() (used in NetBeans visual
GUI builder) or createAndShowGUI() to handle all the
GUI codes (and another method called initGame() to
handle initialization of the game's objects). This GUI init
method shall be run in the event-dispatching thread.