Java Chapter One
Java Chapter One
Chapter 1
GUI: Java AWT and Swing
1. Introduction
A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an
application. It gives an application a distinctive “look and feel.” GUIs are built from GUI
components. These are sometimes called controls or widgets—short for window gadgets. A
GUI component is an object with which the user interacts via the mouse, the keyboard or another
form of input, such as voice recognition.
Many IDEs provide GUI design tools with which you can specify a component’s exact size and
location in a visual manner by using the mouse. The IDE generates the GUI code for you.
Though this greatly simplifies creating GUIs, each IDE generates this code differently. For this
reason, we wrote the GUI code by hand.
The JFC is a suite of libraries designed to assist programmers in creating enterprise applications
with Java. The Java Foundation Classes (JFC) consists of five major parts: AWT, Swing,
Accessibility support, Java 2D, and Drag and Drop. Java 2D has become an integral part of
AWT, Swing is built on top of AWT, and Accessibility support is built into Swing.
The five parts of JFC are certainly not mutually exclusive, and Swing is expected to merge more
deeply with AWT in future versions of Java. Thus, AWT is at the core of JFC, which in turn
makes it one of the most important libraries in Java 2.
The AWT and Swing API are the primary focus of this class, here is a brief introduction to these
elements in the JFC:
AWT
The Abstract Window Toolkit is the basic GUI toolkit shipped with all versions of the
Java Development Kit. It is a set of classes intended to provide everything a developer
needs to create a graphical interface for any Java applet or application.
Accessibility
The accessibility package provides assistance to users who have trouble with traditional
user interfaces. Accessibility tools can be used in conjunction with devices such as
audible text readers or Braille keyboards to allow direct access to the Swing components.
2D API
The 2D API contains classes for implementing various painting styles, complex shapes,
fonts, and colors.
Drag and Drop (DnD) is one of the more common metaphors used in graphical interfaces
today. The user is allowed to click and "hold" a GUI object, moving it to another window
or frame in the desktop with predictable results.
3. AWT
The Abstract Window Toolkit (AWT) is the part of Java designed for creating user interfaces
and painting graphics and images. Most AWT components are derived from the
java.awt.Component class, as figure 1.1 illustrates. Currently, AWT includes over sixty classes,
but with each new release, the class library evolves to include new features.
Sun Microsystems recognized and acknowledged the shortcomings of AWT and promised a
solution in future releases of the language. Sun had to provide a new class library. This new class
library would eventually become known as Swing, and would include all of the advanced classes
that developers expect. Swing is still not a perfect API, but it is certainly a technological leap
forward.
4. Swing
Swing is a large set of components ranging from the very simple, such as labels, to the very
complex, such as tables, trees, and styled text documents. Almost all Swing components are
derived from a single parent called JComponent which extends the AWT Container class. For
this reason, Swing is best described as a layer on top of AWT rather than a replacement for it.
Figure 1.2 shows a partial JComponent hierarchy.
If you compare this with the AWT Component hierarchy of figure 1.1, you will notice that each
AWT component has a Swing equivalent that begins with the prefix “J.” The only exception to
this is the AWT Canvas class, for which JComponent, JLabel, or JPanel can be used as a
replacement (The AWT Canvas class can be replaced by a simple subclass of JComponent). You
will also notice many Swing classes that don’t have AWT counterparts. Figure 1.2 represents
only a small fraction of the Swing library, but this fraction contains the classes you will be
dealing with the most. The rest of Swing exists to provide extensive support and customization
capabilities for the components these classes define.
Swing Components:
• Usually start with ‘J’:
• All components are lightweight (written in Java) except:
– Japplet
– Jframe
– Jwindow
– Jdialog
• AWT components have Swing analogs
Most applications you use on a daily basis use windows or dialog boxes (also called dialogs) to
interact with the user. For example, an e-mail program allows you to type and read messages in a
window the program provides. Dialog boxes are windows in which programs display important
messages to the user or obtain information from the user. Java’s JOptionPane class (package
javax.swing) provides prebuilt dialog boxes for both input and output. These are displayed by
invoking static JOptionPane methods. Figure 1.4 presents a simple addition application that uses
two input dialogs to obtain integers from the user and a message dialog to display the sum of
the integers the user enters.
Figure 1.4 Addition program that uses JOptionPane for input and output.
In Java’s early days, GUIs were built with components from the Abstract Window Toolkit
(AWT) in package java.awt. These look like the native GUI components of the platform on
which a Java program executes. For example, a Button object displayed in a Java program
running on Microsoft Windows looks like those in other Windows applications. On Apple Mac
OS X, the Button looks like those in other Mac applications. Sometimes, even the manner in
which a user can interact with an AWT component differs between platforms. The component’s
appearance and the way in which the user interacts with it are known as its look-and-feel.
Swing GUI components allow you to specify a uniform look-and-feel for your application across
all platforms or to use each platform’s custom look-and-feel. An application can even change the
look-and-feel during execution to enable users to choose their own preferred look-and-feel.
Most Swing components are lightweight components; they’re written, manipulated and
displayed completely in Java. AWT components are heavyweight components, because they
rely on the local platform’s windowing system to determine their functionality and their look-
and-feel. Several/not many Swing components are heavyweight components.
Class Component (package java.awt) is a super class that declares the common features of GUI
components in packages java.awt and javax.swing. Any object that is a Container (package
java.awt) can be used to organize Components by attaching the Components to the Container.
Containers can be placed in other Containers to organize a GUI. Class JComponent (package
javax.swing) is a subclass of Container, see figure 1.5. JComponent is the super class of all
lightweight Swing components and declares their common attributes and behaviors. Because
JComponent is a subclass of Container, all lightweight Swing components are also Containers.
Most windows you’ll create can contain Swing GUI components which are instances of class
JFrame or a sub class of JFrame. JFrame is an indirect sub class of class java.awt.window that
provides the basic attributes and behaviors of a window; a title bar at the top, and buttons to
minimize, maximize and close the window.
GUI designers often provide text stating the purpose of each. Such text is known as a label and is
created with a JLabel; a subclass of JComponent. A JLabel displays read-only text, an image,
or both text and an image.
When building a GUI, you must attach each GUI component to a container, such as a window
created with a JFrame. Also, you typically must decide where to position each GUI component;
known as specifying the layout.
Java provides several layout managers that can help you position components. Many IDEs
provide GUI design tools in which you can specify components’ exact sizes and locations in a
visual manner by using the mouse; then the IDE will generate the GUI code for you. Such IDEs
can greatly simplify GUI creation.
Java’s layout managers are used to size and position components. With the FlowLayout layout
manager, components are placed on a container from left to right in the order in which they’re
added. When no more components can fit on the current line, they continue to display left to
right on the next line. If the container is resized, a Flow- Layout reflows the components,
possibly with fewer or more rows based on the new container width. Every container has a
default layout, which we’re changing for LabelFrame to a FlowLayout (line 20, figure 1.6).
Method setLayout is inherited into class LabelFrame indirectly from class Container. The
argument to the method must be an object of a class that implements the LayoutManager
interface (e.g., FlowLayout). Line 20 creates a new FlowLayout object and passes its reference
as the argument to setLayout.
Class LabelTest (Fig. 1.7) creates an object of class LabelFrame (line 9), then specifies the
default close operation for the window. By default, closing a window simply hides the window.
However, when the user closes the LabelFrame window, we would like the application to
terminate. Line 10 invokes LabelFrame’s setDefaultCloseOperation method (inherited from
class JFrame) with constant JFrame.EXIT_ON_CLOSE as the argument to indicate that the
program should terminate when the window is closed by the user. This line is important. Without
it the application will not terminate when the user closes the window. Next, line 11 invokes
LabelFrame’s setSize method to specify the width and height of the window in pixels. Finally,
line 12 invokes LabelFrame’s setVisible method with the argument true to display the window
on the screen. Try resizing the window to see how the FlowLayout changes the JLabel positions
as the window width changes.
6. Text Fields
Swing provides an extensive collection of classes for working with text in user interfaces. In fact,
because there's so much provided for working with text, Swing's creators placed most of it into
its own package: javax.swing.text. This package's dozens of interfaces and classes (plus the six
concrete component classes in javax.swing) provide a rich set of text-based models and
components complex enough to allow endless customization yet simple to use in the common
case. JTextComponent is the base class for the text components such as JTextField,
JPasswordField and JTextArea.
Events are actions usually triggered by the system user or by the actions of objects; for instance,
clicking a button.
When the user types in a JTextField or a JPasswordField, then presses Enter, an event occurs.
Our next example demonstrates how a program can perform a task in response to that event. The
techniques shown here are applicable to all GUI components that generate events.
The application of Figs. 1.8–1.9 below uses classes JTextField and JPasswordField to create and
manipulate four text fields. When the user types in one of the text fields, then presses Enter, the
application displays a message dialog box containing the text the user typed. You can type only
in the text field that’s “in focus.” When you click a component, it receives the focus. This is
important, because the text field with the focus is the one that generates an event when you press
Enter. In this example, you press Enter in the JPasswordField, the password is revealed. We
begin by discussing the setup of the GUI, then discuss the event-handling code. Lines 3–9 import
the classes and interfaces we use in this example. Class TextField- Frame extends JFrame and
declares three JTextField variables and a JPasswordField variable (lines 13–16). Each of the
corresponding text fields is instantiated and attached to the TextFieldFrame in the constructor
(lines 19–47).
Normally, a user interacts with an application’s GUI to indicate the tasks that the application
should perform. For example, when you write an e-mail in an e-mail application, clicking the
Send button tells the application to send the e-mail to the specified e-mail addresses. GUIs are
event driven. When the user interacts with a GUI component, the interaction— known as an
event—drives the program to perform a task. Some common user interactions that cause an
application to perform a task include clicking a button, typing in a text field, selecting an item
from a menu, closing a window and moving the mouse. The code that performs a task in
response to an event is called an event handler, and the overall process of responding to events
is known as event handling. Let’s consider two other GUI components that can generate
events—JTextFields and JPasswordFields (package javax.swing). Class JTextField extends
class JTextComponent (package javax.swing.text), which provides many features common to
Swing’s text-based components. Class JPasswordField extends JTextField and adds methods that
are specific to processing passwords. Each of these components is a single-line area in which the
user can enter text via the keyboard. Applications can also display text in a JTextField. A
JPasswordField shows that characters are being typed as the user enters them, but hides the
actual characters with an echo character, assuming that they represent a password that should
remain known only to the user.
Mouse click / Key press, Menu Selection, Timer expiring, Network message received are all
Event Sources. Some GUI components might care about one of these things happening and need
to react to it. These components would register themselves with the Event Source, so the source
would tell them when something happens. These are the Event Listeners.
Compiled by: Firomsa Ta, Lecturer at BHU.Page 15
Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing
This example should display a message dialog containing the text from a text field when the user
presses Enter in that text field. Before an application can respond to an event for a particular GUI
component, you must:
1. Create a class that represents the event handler and implements an appropriate interface—
known as an event-listener interface.
2. Indicate that an object of the class from Step 1 should be notified when the event occurs—
known as registering the event handler.
Class TextFieldTest (Fig. 1.9 below) contains the main method that executes this application and
displays an object of class TextFieldFrame.
The event object encapsulates information about the event that occurred, such as a reference to
the event source and any event-specific information that may be required by the event listener for
it to handle the event. The event listener is an object that’s notified by the event source when an
event occurs; in effect, it “listens” for an event, and one of its methods executes in response to
the event. A method of the event listener receives an event object when the event listener is
notified of the event. The event listener then uses the event object to respond to the event. This
event-handling model is known as the delegation event model—an event’s processing is
delegated to an object (the event listener) in the application. In the above figure 1.8 line 42
“handler” is event object or event handler object while from line 43 up to 46; textField1,
textField2, textField3 and passwordField are all event listeners.
The class for an event must implement the appropriate event-listener interface. Forgetting to
register an event-handler object for a particular GUI component’s event type causes events of
that type to be ignored.