0% found this document useful (0 votes)
56 views17 pages

Java Chapter One

The document discusses Java's GUI frameworks AWT and Swing. It begins by introducing GUI components and how IDEs can assist with GUI design. It then describes the Java Foundation Classes (JFC) which include AWT, Swing, Java 2D, accessibility support and drag and drop. The core of AWT and the layered Swing API built on top of AWT are the focus. Key AWT and Swing components like buttons, text fields, menus and dialog boxes are defined along with differences in look and feel between platforms. Examples are provided on creating simple GUIs using JOptionPane dialog boxes and basic Swing components.

Uploaded by

Teda Tech Tips
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
56 views17 pages

Java Chapter One

The document discusses Java's GUI frameworks AWT and Swing. It begins by introducing GUI components and how IDEs can assist with GUI design. It then describes the Java Foundation Classes (JFC) which include AWT, Swing, Java 2D, accessibility support and drag and drop. The core of AWT and the layered Swing API built on top of AWT are the focus. Key AWT and Swing components like buttons, text fields, menus and dialog boxes are defined along with differences in look and feel between platforms. Examples are provided on creating simple GUIs using JOptionPane dialog boxes and basic Swing components.

Uploaded by

Teda Tech Tips
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

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.

Different 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.

2. Java Foundation Classes (JFC)

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.

To be honest JFC is not nearly as fancy as MCF.

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.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 1


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

2D API

The 2D API contains classes for implementing various painting styles, complex shapes,
fonts, and colors.

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.

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.

What are components?


Components are elements of GUI which can be referred as controls or widgets. Figure 1.1 shows
some elements or components of AWT hierarchically.

• Button:- A push component.


• Canvas:- A general purpose component that lets you paint and create graphics.
• Checkbox:- Has “on” or “off” state. You can place in group that allows at most one box
checked.
• Choice:- Select one from group of choices.
• Label:- A component that displays a static string at a certain location.
• List:- List of items that may be scrolled.
• Textarea:- Multiple lines of texts.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 2


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

• Textfields:- Single line of text.


• Container:- a special component that can hold other components. For instance: Panel,
windows, applets, frames.
Top level windows:

✓ Window:- A top level window that has no border.


✓ Frame:- A top level window that has border.
✓ Dialog:- A top level window used to create dialogs. One sub class of this is the FileDialog.
Windows that programs display to the user along with some messages or to obtain
information from the users, fig 1.4.
✓ Panel:- Subclass of container class to store collections of objects. It doesn’t create a separate
window of its own.

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

Compiled by: Firomsa Ta, Lecturer at BHU.Page 3


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

– Jdialog
• AWT components have Swing analogs

AWT to Swing Mappings


• Almost all map by prepending a ‘J’
Examples:
– Button -> Jbutton
– Panel -> Jpanel
– List -> Jlist
Exceptions:
– Checkbox -> JCheckBox (note case change)
– Choice -> JComboBox

Some New Components:


• Jtree :- Creates a tree, whose nodes can be expanded.
• Jtable:-Used to display tables (for instance, those obtained from databases)
• Tooltips:- Use setToolTipText to install a tooltip. Works for any JComponent.
Jbutton b = new Jbutton( "Quit" );
b.setToolTipText("Press to quit");
• JPopupMenu :- Appears when you right-click on a component
• JOptionPane :- Contains static methods that pop up a modal dialog. Commonly used
methods are:
showMessageDialog( )
showConfirmDialog( )
showInputDialog( )

Where to declare Components?

Components are typically declared in one of several places:


• Field variables: Some components should be declared as field variables (instance variables,
member variables). This is the appropriate place to declare components which must be
referenced after the interface is constructed. Typically these are text fields or text areas,
check boxes, etc.
• Local variables: Local variables should be used for components which are never referenced
after the interface is constructed. Typically these are panels for holding components, buttons
(whose interaction is thru their listeners), ...
• Anonymous: Anonymous creation is typical with labels, which can be created and added in
one step and never assigned to a variable.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 4


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

Figure 1.3 Some basic Swing Components description

Compiled by: Firomsa Ta, Lecturer at BHU.Page 5


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

Example 1: Simple GUI-Based Input/Output with JOptionPane

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.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 6


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

Figure 1.4 Addition program that uses JOptionPane for input and output.

5. Swing vs. AWT


Look and Feel Observation:

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.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 7


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

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.

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

Generally, AWT and Swing:


• Concepts are all the same.
• AWT is more portable; Swing is better looking.
• AWT lays out inconsistently on different OSs).
• Most old AWT is easily translated: Add J in front of the class names.
• AWT Uses peer components of the OS; heavyweight components.
• Swing has easy-to-use new stuff including tooltips, mnemonics, borders, JOptionPane.
• Swing 99% java; lightweight components.
• Swing lays out consistently on all OSs.
• Swing uses AWT event handling.
• Unlike AWT components, Swing components are not implemented by platform-specific
code. Instead they are written entirely in Java and therefore are platform-independent. The
term "lightweight" is used to describe such an element.
• Swing provides replacements for most of the AWT components, although many AWT non-
component classes remain in use.
• Upward compatibility is assured in almost all cases; an AWT continues to work in Java.
• Mixing both Swing and AWT components in the same interface can produce errors, so one
has to make a decision about which to use.
• Swing advantages:
• Swing is faster.
• Swing is more complete.
• Swing is being actively improved.
• AWT advantages:
• AWT is supported on older, as well as newer, browsers so Applets written in AWT
will run on more browsers.
• The Java Micro-Edition, which is used for phones, TV settop boxes, PDAs, etc, uses
AWT, not Swing.

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

Compiled by: Firomsa Ta, Lecturer at BHU.Page 8


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

lightweight Swing components and declares their common attributes and behaviors. Because
JComponent is a subclass of Container, all lightweight Swing components are also Containers.

Figure 1.5 Common super classes of the lightweight Swing components.

Some common features supported by JComponent include:

1. A pluggable look-and-feel for customizing the appearance of components (e.g.,for use on


particular platforms).
2. Shortcut keys (called mnemonics) for direct access to GUI components through the
keyboard.
3. Brief descriptions of a GUI component’s purpose (called tool tips) that are displayed when
the mouse cursor is positioned over the component for a short time.
4. Support for accessibility, such as braille screen readers for the visually impaired.
5. Support for user-interface localization—that is, customizing the user interface to display in
different languages and use local cultural conventions.

Example 2: Displaying Text and Images in a Window

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.

Labeling GUI 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.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 9


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

Figure 1.6 JLabels with text and icons.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 10


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

Figure 1.7 Test class for LabelFrame.

Specifying the Layout

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.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 11


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

The above codes (fig 1.6 and 1.7) used to:

✓ Specifying the Layout


✓ Loading an Image Resource
There are two ways to position a component in a container:
1. Using a predefined layout and allowing the layout to decide where to position the
component.
• This is a soft way of positioning a component. If the container changes its size, the
component's position will be adjusted.
• But you may not able to get precisely where you want.
2. Specifying the position of the component using the container's coordinates.
• This is a hard way of positioning a component.
• You can get precisely where you want the component to be. But if the container
changes its size, the component's position will not be adjusted.

Creating and Displaying a LabelFrame Window

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.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 12


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

Compiled by: Firomsa Ta, Lecturer at BHU.Page 13


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

Figure 1.8 JTextFields and JPasswordFields

Compiled by: Firomsa Ta, Lecturer at BHU.Page 14


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

7. Event and Event Handling


Events come from User Controls

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.

Every Input Control (Button, Slider ...) Needs an Event Listener


If you want a control to do something when the user alters the control, you must have a listener.

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

To use events, you must import :


▪ import java.awt.*;
▪ import java.awt.event.*;
▪ import javax.swing.*;
▪ import javax.swing.event.*;

There are several kinds of events. The most common are:

User Control addXXXListener method in listener


Button/JButton
TextField/JTextField addActionListener() actionPerformed(ActionEvent e)
MenuItem/JMenuItem
Slider/Jslider addChangeListener() stateChanged(ChangeEvent e)
CheckBox/JCheckBox addItemListener() itemstateChanged()
key on component addKeyListener() keyPressed(), keyReleased(), keyTyped()
mouseClicked(),
mouseEntered(),
mouse on component addMouseListener()
mouseExited(),
mousePressed(), mouseReleased()
mouseMoved(),
mouse on component addMouseMotionListener()
mouseDragged()
Frame/JFrame addWindowListener() windowClosing(WindowEvent e), ...

Steps Required to Set Event Handling for a GUI Component

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.

Compiled by: Firomsa Ta, Lecturer at BHU.Page 16


Advanced Programming (CoSc2084) Chapter One GUI: AWT and Swing

Figure 1.9 Test class for 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.

Reading Assignment: Adapter Classes

Compiled by: Firomsa Ta, Lecturer at BHU.Page 17

You might also like