0% found this document useful (0 votes)
249 views16 pages

Chapter One: Abstract Window Toolkit (AWT) and Swing

This document discusses the Abstract Window Toolkit (AWT) and Swing graphical user interface (GUI) frameworks in Java. It covers the key components of the Java Foundation Classes (JFC) including AWT, accessibility, 2D, and drag-and-drop APIs. It then describes common Swing GUI components like JFrame, JLabel, JTextField, JPasswordField and JButton. It explains the differences between heavyweight and lightweight components and how Swing components inherit from classes like JComponent and Container.

Uploaded by

Minalew Guche
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
249 views16 pages

Chapter One: Abstract Window Toolkit (AWT) and Swing

This document discusses the Abstract Window Toolkit (AWT) and Swing graphical user interface (GUI) frameworks in Java. It covers the key components of the Java Foundation Classes (JFC) including AWT, accessibility, 2D, and drag-and-drop APIs. It then describes common Swing GUI components like JFrame, JLabel, JTextField, JPasswordField and JButton. It explains the differences between heavyweight and lightweight components and how Swing components inherit from classes like JComponent and Container.

Uploaded by

Minalew Guche
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Dep’t of Computer Science Advanced Programing Cosc2084

CHAPTER ONE
Abstract window Toolkit (AWT) and Swing

1. The Java Foundation Classes (JFC)

The FC is a suite of libraries designed to assist programmers in creating enterprise applications


with Java. The swing API is only one of five libraries that make up the JFC. The JFC also
consists of the Abstract Window Toolkit (AWT), the accessibility API, the 2D API and enhanced
support for Drag and Drop capabilities.

AWT

The Abstract Window Toolkit is the basic GUI toolkit shipped with all versions of the Java
Development Kit. While Swing does not reuse any of the older AWT components, it does build
on the lightweight component facilities introduced in AWT 1.1.

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. Accessibility is split
into two parts: the Accessibility API, which is shipped with the Swing distribution, and the
Accessibility Utilities API, which is distributed separately. All Swing components support
accessibility.

2D API

The 2D API contains classes for implementing various painting styles, complex shapes, fonts,
and colors. This Java package is loosely based on APIs that were licensed from IBM's Taligent
division. The 2D API classes are not part of Swing.

Drag and Drop

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. The DnD API allows users to implement droppable
elements that transfer information between Java applications and native applications. Although
DnD is not part of Swing, it is crucial to a commercial-quality application.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure 1.1 The five API’s of the JFC

2. Graphical User Interface (GUI) components

A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an
application. A GUI (pronounced “GOO-ee”) 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.

IDE Support for GUI Design


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.

Swing vs. AWT


There are actually two sets of Java GUI components. In Java’s early days, GUIs were built with
components from the Abstract Window Toolkit (AWT) in package [Link]. 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.

Lightweight vs. Heavyweight GUI Components


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 Swing components are heavyweight components.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Super classes of Swing’s Lightweight GUI Components


The UML class diagram of Fig. 1.2 shows an inheritance hierarchy of classes from which
lightweight Swing components inherit their common attributes and behaviors.

Figure 1.2 Common superclasses of the lightweight Swing components.

Class Component (package [Link]) is a superclass that declares the common features of GUI
components in packages [Link] and [Link]. Any object that is a Container (package
[Link]) 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
[Link]) is a subclass of Container. JComponent is the superclass 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. Some common
features supported by JComponent include:

Comparison of AWT and Swing


[Link] [Link]
Frame JFrame
Panel JPanel
Canvas JPanel
Label JLabel
Button JButton
TextField JTextField
Checkbox JCheckBox
List JList
Choice JComboBox

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure 1.3 Part of class hierarchy

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure 1.4 Swing application demonstrates many of Java’s Swing GUI components.

JFrame and JLabel


Most windows you’ll create that can contain Swing GUI components are instances of class
JFrame or a subclass of JFrame. JFrame is an indirect subclass of class [Link] 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. Since an application’s GUI is typically specific to
the application, most of our examples will consist of two classes a subclass of JFrame that helps
us demonstrate new GUI concepts and an application class in which main creates and displays
the application’s primary window.
A window with a title bar, a resizable border, and possibly a menu bar.
 A frame is not attached to any other surface.
 It has a content pane that acts as a container.
 The container uses BorderLayout by default.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure 1.5 the JFrame form


A layout manager, an instance of one of the layout classes, describes how components are placed
on a container.
Creating a JFrame
import [Link];
public class LabelTest
{
public static void main( String[] args )
{
LabelFrame labelFrame = new LabelFrame(); // create LabelFrame
[Link]( JFrame.EXIT_ON_CLOSE );
[Link]( 260, 180 ); // set frame size
[Link]( true ); // display frame
}
}

Labeling GUI Components


A typical GUI consists of many components. 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. Applications
rarely change a label’s contents after creating it. Text in a JLabel normally uses sentence-style
capitalization.
Labels are components consisting of a String to be placed on a container.
 Used to label another component.
 Used as output on a container.
Example

Figure 1.6 Demonstrating out of JLabel

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

JTextField and JPasswordField


JTextFields and JPasswordFields (package [Link]) are single-line areas in which text can
be entered by the user from the keyboard or text can simply be displayed. A JPasswordField
shows that a character was typed as the user enters characters, but hides the characters, assuming
that they represent a password that should remain known only to the user. When the user types
data into a JTextField or JPasswordField and presses the Enter key, an action event occurs. If
the program registers an event listener, the listener processes the event and can use the data in the
JTextField or JPasswordField at the time of the event in the program. Class JTextField
extends class JTextComponent (package [Link]), which provides many features
common to Swing’s text-based components. Class JPasswordField extends JTextField and
adds several methods that are specific to processing passwords.

Figure 1.7 Demonstrating out of JTextFields and JPasswordFields


JButton
A button is a component the user clicks to trigger a specific action. A Java program can use
several types of buttons, including command buttons, check boxes, toggle buttons and radio
buttons. Figure 1.8 shows the inheritance hierarchy of the Swing buttons. As you can see in the
diagram, all the button types are subclasses of Abstract- Button (package [Link]), which
defines many of the features that are common to Swing buttons. In this section, we concentrate
on buttons that are typically used to initiate a command. A command button generates an
ActionEvent when the user clicks the button with the mouse. Command buttons are created with
class JButton, which inherits from class AbstractButton. The text on the face of a JButton is
called a button label. A GUI can have many JButtons, but each button label typically should be
unique.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure 1.8 The button hierarchy

Figure 1.9 The command button’s and actions events


JCheckBox and JRadioButton
The Swing GUI components contain three types of state buttons JToggleButton, JCheckBox
and JRadioButton that have on/off or true/false values. JToggleButtons are frequently used
with toolbars (sets of small buttons typically located on a bar across the top of a window).
Classes JCheckBox and JRadioButton are subclasses of JToggleButton. A JRadioButton is
different from a JCheckBox in that there are normally several JRadioButtons that are grouped
together and only one of the JRadioButtons in the group can be selected (true) at any time.
The application of Fig. 1.10 uses two JCheckBox objects to change the font style of the text
displayed in a JTextField. One JCheckBox applies a bold style when selected and the other
applies an italic style when selected. If both are selected, the style of the font is bold and italic.
When the program initially executes, neither JCheckBox is checked (true).

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

1.10 The checkbox demonstration output


Radio buttons (defined with class JRadioButton) are similar to check boxes in that they have
two states selected and not selected (also called deselected). However, radio buttons normally
appear as a group in which only one radio button can be selected at a time. Selecting a different
radio button in the group automatically forces all other radio buttons in the group to be
deselected. Radio buttons are used to represent a set of mutually exclusive options (i.e., multiple
options in the group would not be selected at the same time). The logical relationship between
radio buttons is maintained by a ButtonGroup object (package [Link]). The
ButtonGroup object itself is not a GUI component. Therefore, a ButtonGroup object is not
displayed in a user interface. Rather, the individual JRadioButton objects from the group are
displayed in the GUI. The application of Fig. 1.11 is similar to the preceding program. The user
can alter the font style of a JTextField’s text. The program uses radio buttons that permit only a
single font style in the group to be selected at a time.

Figure 1.11 the demonstrating output of creating and manipulating radio button
JComboBox
A combo box (sometimes called a drop-down list) provides a list of items from which the user
can make a selection. Combo boxes are implemented with class JComboBox, which inherits
from class JComponent. JComboBoxes generate ItemEvents like JCheckBoxes and
JRadioButtons. The application of Fig. 1.12 uses a JComboBox to provide a list of four image
file names. When an image file name is selected, the corresponding image is displayed as an
Icon on a JLabel. The screen captures for this program show the JComboBox list after the
selection was made to illustrate which image file name was selected.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure 1.12 the demonstrating output for JComboBox


JList
A list displays a series of items from which the user may select one or more items. Lists are
created with class JList, which inherits from class JComponent. Class JList supports single-
selection lists (i.e., lists that allow only one item to be selected at a time) and multiple-selection
lists (lists that allow any number of items to be selected). In this section, we discuss single-
selection lists.
The application of Fig. 1.13 creates a JList of 13 colors. When a color name is clicked in the
JList, a ListSelectionEvent occurs and the application window content pane’s background color
changes.

Figure 1.13 the demonstration output selecting colors from a JList


Multiple-Selection Lists
A multiple-selection list enables the user to select many items from a Jlist. A Single interval
selection list allows selection of a contiguous range of items in the list by clicking the first item,
then holding the shift key while clicking the last item to select in the range. A multiple interval
selection list allows continuous Range selection as described for a single interval selection list
and allows miscellaneous Items to be selected by holding the ctrl key (sometimes called to
control Key)while clicking each item to select. To deselect an item, hold the ctrl key while
clicking the item a second time. The application of fig. 1.14 uses multiple-selection lists to copy
items from one Jlist to another. One list is a multiple interval selection list and the other is a
single interval selection list. When you execute the program, try using the selection techniques
described above to select items in both lists.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure. 1.14 the demonstration output for multiple selection lists


A multiple-selection list does not have a specific event associated with making multiple
selections. Normally, an event generated by another GUI component (known as an external
event) specifies when the multiple selections in a JList should be processed. In this example, the
user clicks JButton copyButton to trigger the event that copies the selected items in colorList
to copyList.

Mouse Event Handling


This section presents the MouseListener and MouseMotionListener event-listener interfaces
for handling mouse events. Mouse events can be trapped for any GUI component that derives
from [Link]. The methods of interfaces MouseListener and
MouseMotionListener are summarized in Figure 1.15. Each of the mouse event handling
methods takes a MouseEvent object as its argument. A MouseEvent object contains
information about the mouse event that occurred, including the x- and y-coordinates of the
location where the event occurred. The MouseListener and MouseMotionListener methods are
called automatically when the mouse interacts with a Component if listener objects are
registered for a particular Component. Method mousePressed is called when a mouse button is
pressed with the mouse cursor over a component. Using methods and constants of class
InputEvent (the superclass of MouseEvent), a program can determine which mouse button the
user clicked. Method mouseClicked is called whenever a mouse button is released without
moving the mouse after a mousePressed operation. Method mouseReleased is called whenever
a mouse button is released. Method mouseEntered is called when the mouse cursor enters the
physical boundaries of a Component. Method mouseExited is called when the mouse cursor
leaves the physical boundaries of a Component. Method mouseDragged is called when the
mouse button is pressed and held, and the mouse is moved (a process known as dragging). The
mouseDragged event is preceded by a mousePressed event and followed by a mouseReleased
event. Method mouseMoved is called when the mouse is moved with the mouse cursor over a
component (and no mouse buttons pressed). The MouseTracker application demonstrates the
MouseListener and MouseMotionListener methods. The application class implements both
interfaces so it can listen for its own mouse events. Note that all seven methods from these two
interfaces must be defined by the programmer when a class implements both interfaces.
The message dialog box in the sample output windows appears when the user moves the mouse
into the application window.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure 1.15 each mouse event results in a String displayed in JLabel statusBar at the
Button of the window.
Keyboard Event Handling
This section presents the KeyListener eventlistener interface for handling key events. Key
events are generated when keys on the keyboard are pressed and released. A class that
implements KeyListener must provide definitions for methods keyPressed, keyReleased and
keyTyped, each of which receives a KeyEvent as its argument. Class KeyEvent is a subclass of
InputEvent. Method keyPressed is called in response to pressing any key. Method keyTyped is
called in response to pressing any key that is not an action key (e.g., an arrow key, Home, End,
Page Up, Page Down, a function key, Num Lock, Print Screen, Scroll Lock, Caps Lock and
Pause). Method keyReleased is called when the key is released after any keyPressed or
keyTyped event. Figure 1.16 demonstrates the KeyListener methods. Class KeyDemo
implements the KeyListener interface, so all three methods are defined in the application.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure 1.16 demonstration output for keyboard event

FlowLayout
FlowLayout is the most basic layout manager. GUI components are placed on a container from
left to right in the order in which they are added to the container. When the edge of the container
is reached, components are continued on the next line. Class FlowLayout allows GUI
components to be left-aligned, centered (the default) and right-aligned. The application of Fig.
1.17 creates three JButton objects and adds them to the application, using a FlowLayout layout
manager. The components are automatically center-aligned. When the user clicks Left, the
alignment for the layout manager is changed to a left-aligned FlowLayout. When the user clicks
Right, the alignment for the layout manager is changed to a right-aligned FlowLayout. When
the user clicks Center, the alignment for the layout manager is changed to a center-aligned
FlowLayout. Each button has its own event handler that is defined with an inner class that
implements ActionListener. The sample output windows show each of the FlowLayout
alignments. Also, the last sample output window shows the centered alignment after the window
has been resized to a smaller width. Notice that the button Right now appears on a new line.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure. 1.17 Program that demonstrates components in FlowLayout


BorderLayout
The BorderLayout layout manager (the default layout manager for the content pane) arranges
components into five regions: NORTH, SOUTH, EAST, WEST and CENTER (North
corresponds to the top of the container). Class BorderLayout inherits from Object and
implements interface LayoutManager2 (a subinterface of LayoutManager that adds several
methods for enhanced layout processing). Up to five components can be added directly to a
BorderLayout—one for each region. The component placed in each region can be a container to
which other components are attached. The components placed in the NORTH and SOUTH
regions extend horizontally to the sides of the container and are as tall as the components placed
in those regions. The EAST and WEST regions expand vertically between the NORTH and
SOUTH regions and are as wide as the components placed in those regions. The component
placed in the CENTER region expands to take all remaining space in the layout (this is the
reason the JTextArea in Fig. 1.17 occupies the entire window). If all five regions are occupied,
the entire container’s space is covered by GUI components. If the NORTH or SOUTH region is
not occupied, the GUI components in the EAST, CENTER and WEST regions expand
vertically to fill the remaining space. If the EAST or WEST region is not occupied, the GUI
component in the CENTER region expands horizontally to fill the remaining space. If the
CENTER region is not occupied, the area is left empty—the other GUI components do not
expand to fill the remaining space.

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

Figure. 1.17 demonstration result for borderlayout


GridLayout
The GridLayout layout manager divides the container into a grid so that components can be
placed in rows and columns. Class GridLayout inherits directly from class Object and
implements interface LayoutManager. Every Component in a GridLayout has the same width
and height. Components are added to a GridLayout starting at the topleft cell of the grid and
proceeding left-to-right until the row is full. Then the process continues left-to-right on the next
row of the grid, etc. Figure 1.18 demonstrates the GridLayout layout manager using six
JButtons.

Figure 1.18 demonstration result for gridlayout


Panels
Complex GUIs require that each component be placed in an exact location. They often consist of
multiple panels with each panel’s components arranged in a specific layout. Panels are created

Compiled By G.T
Dep’t of Computer Science Advanced Programing Cosc2084

with class JPanel—a subclass of JComponent. Class JComponentinherits from class


[Link], so every JPanel is a Container. Thus JPanels may have components,
including other panels, added to them.
The program of Figure. 1.19 demonstrates how a JPanel can be used to create a more complex
layout for Components.

Figure. 1.19 demonstration output for Panel

Compiled By G.T

You might also like