Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 48

CHAPTER 1

AWT AND SWING

Introduction
UI
 The user interface (UI) is the space where interactions between
humans and machines occur.
 The goal of this interaction is to allow effective operation and
control of the machine from the human end
 whilst the machine simultaneously feeds back information that aids
the operators' decision-making process.

 There are two types of user interface: command-line user interface


(CLI) and graphical user interface (GUI).
 A CLI is a means of interacting with a computer program where
the user issues commands to the program in the form of successive
lines of text (command lines).
 The CLI was the primary means of interaction with most computer
systems until the introduction of the GUI.
GUI…
 A GUI offers user interaction via graphical components.
 For example, OS System offers GUI via window, Dialog,
Button, Textfield, TextArea, Listbox, Combobox, Label,
Checkbox etc.
 These all are known as GUI components.
 Using these components, we can create an interactive user
interface for an application.
 A GUI presents a pictorial interface to a program.
 A GUI gives a program a distinctive “look” and “feel”.
 GUIs are built from GUI components called controls or widgets.
 A GUI component is an object with which the user interacts via
the mouse, the keyboard or another form of input.
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.
 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.
JFC…
 The Accessibility package provides assistance(help/support) 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.
 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(likeness/analogy/similarity b/n objects) 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.
JFC…
 There are two basic sets of GUI components in Java: the
Abstract Window Toolkit (AWT) and Swing.
 Both of these groups of components are part of the Java
Foundation Classes (JFC).
 The original(old) GUI for Java was called the Abstract
Windowing Toolkit (AWT).
 Performance and extendibility problems with AWT were
resolved by introducing a new(modern) GUI interface, known as
Swing.
 Swing provides replacements for most of the AWT
components, although many AWT non-component classes
remain in use.
AWT
 AWT stands for 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.
 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.
 Components are elements of GUI which can be referred as
controls or widgets.
 Figure 1.1 shows some elements or components of AWT
hierarchically.
AWT…
 These are the major components you can work with in the AWT:
 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.
 Textfields:- Single line of text.
 Container:- a special component that can hold other components. For
instance: Panel, windows, applets, frames.
AWT…
 Top level windows of Container class:
 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 File Dialog.
 Windows that programs display to the user along with
some messages or to obtain information from the users.
 Panel:- Subclass of container class to store collections of
objects.
 It doesn’t create a separate window of its own.
Swing
 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(to be wait).
 Swing is still not a perfect API, but it is certainly a
technological leap(to move on step forward) forward.
 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.
Swing…
 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.
 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.
Swing Components:
 Usually start with ‘J’:
 All components are lightweight (written in Java)

except:
 Japplet
 Jframe
 Jwindow
 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:(are a variables declared within a class but outside any method) 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:(are a variables that are declared within method, constructor or block of
code) 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:(when you need to create a class that is used only one and does not need to be reused in
other parts of the code) Anonymous creation is typical with labels, which can
be created and added in one step and never assigned to a variable.
Figure 1.3 Some basic Swing Components description
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.
Example 1 …
Example 1 …

Figure 1.4 Addition program that uses JOptionPane for input and output.
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(AWT) are known as its look-and-feel.
Swing vs. AWT…
 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
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.
Generally, AWT and Swing …
 Unlike AWT components, Swing components are not
implemented by platform-specific(dependent) code.
 Instead they are written entirely in Java and therefore are
platform-independent(Swing).
 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
Generally, AWT and Swing …
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.
Generally, AWT and 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.
Generally, AWT and Swing …
 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.

Figure 1.5 Common super classes of the lightweight Swing components.


Generally, AWT and Swing …
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.
Figure 1.6 JLabels with text and icons.
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.
Specifying the Layout …
 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 FlowLayout 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.
Specifying the Layout …
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
Specifying the Layout …
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.
TextField
 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.
 The Swing API provides several classes for components that are
either varieties of text fields or that include text fields:
 JTextField
 JTextArea
 JPasswordField. Etc…
Figure 1.8 JTextFields and JPasswordFields
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.
Event and Event Handling…
 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(displayed).
 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.
Event and Event Handling…
 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
Event and Event Handling…
 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
Event and Event Handling…
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), ...
Event and Event Handling…
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.
Event and Event Handling…

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.
Event and Event Handling…
 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
END…
 Reading Assignment: Adapter Classes

END OF CHAPTER

You might also like