0% found this document useful (0 votes)
22 views94 pages

Bbit2205-01 Awt 2024

Uploaded by

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

Bbit2205-01 Awt 2024

Uploaded by

Yahya Gigi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

BBIT2205-01

Programming GUI with AWT


• Java Graphics APIs - AWT and Swing - provide a
huge set of reusable GUI components, such as
button, text field, label, choice, panel and frame
for building GUI applications.
• You can simply reuse these classes rather than
re-invent the wheels.
• We shall start with the AWT classes before
moving into Swing to give you a complete
picture.
• AWT component classes are now obsoleted by
Swing's counterparts.
Introduction to AWT
• Java AWT (Abstract Windowing Toolkit) is an
API to develop GUI or window-based
application in java.
• AWT contains large number of classes and
methods that allows you to create and
manage windows GUI application
• It is used for GUI programming in Java
Why AWT is platform dependent?
• Java AWT calls native platform (Operating
systems) subroutine for creating components
such as textbox, checkbox, button etc.
• For example an AWT GUI having a button
would have a different look and feel across
platforms like windows, Mac OS & Unix, this is
because these platforms have different look
and feel for their native buttons and AWT
directly calls their native subroutine that
creates the button.
Today’s fate of AWT in GUI
• AWT is rarely used now days because of its
platform dependent and heavy-weight nature.
• AWT components are considered heavy
weight because they are being generated by
underlying operating system (OS).
• For example if you are instantiating a text box
in AWT that means you are actually asking OS
to create a text box for you.
Today’s fate of AWT in GUI
• Swing is a preferred API for window based
applications because of its platform
independent and light-weight nature.
• Swing is built upon AWT API however it
provides a look and feel unrelated to the
underlying platform.
• It has more powerful and flexible components
than AWT.
AWT Hierarchy
Containers and Components
Containers and Components
Containers and Components
• There are two types of GUI elements:
– Component: Components are elementary GUI
entities (such as Button, Label, and TextField.)
– Container: Containers (such as Frame and Panel)
are used to hold components in a specific
layout (such as flow or grid). A container can also
hold sub-containers.
Containers and Components
• GUI components are also
called controls (Microsoft ActiveX
Control), widgets (Eclipse's Standard Widget
Toolkit, Google Web Toolkit), which allow users
to interact with (or control) the application
through these components (such as button-
click and text-entry).
Component class
• All the elements like buttons, text fields,
scrollbars etc are known as components.
• Component class is at the top of AWT hierarchy.
• Component is an abstract class that
encapsulates all attribute of visual component.
• A component object is responsible for
remembering the current foreground and
background colours and the currently selected
text font.
Container
• Containers are integral part of AWT GUI
components
• A Container in AWT is a component itself and it
adds the capability to add component to itself.
• The Container can contain another components
like buttons, textfields, labels etc.
• The classes that extends Container class are
known as container such as Frame, Dialog and
Panel.
Container
• In a GUI program, a component must be kept in a
container.
• You need to identify a container to hold the
components.
• To have everything placed on a screen to a
particular position, we have to add them to a
container.
• A container is like a screen wherein we are
placing components like buttons, text fields,
checkbox etc.
• A container itself is a component (shown in the
above hierarchy diagram) thus we can add a
container inside container.
Container class
• Every container has a method
called add(Component c).
• A container (say aContainer) can
invoke aContainer.add(aComponent) to
add aComponent into itself. For example,
Hierarchy of the
AWT Container Classes
• The hierarchy of the AWT Container classes is
as follows:
Types of containers
• A container is a place wherein we add
components like text field, button, checkbox
etc. There are four types of containers
available in AWT:
– Window,
– Frame,
– Dialog and,
– Panel.
Window
• The window is the container that have no
borders, no title and menu bars.
• You must use frame, dialog or another
window for creating a window.
Panel
• The Panel is the container that doesn't
contain title bar and menu bars.
• It can have other components like button,
textfield etc.
• It provides space in which an application can
attach any other component, including other
panels.
• It uses FlowLayout as default layout manager.
Frame
• The Frame is the container that contain title
bar and can have menu bars.
• It can have other components like button,
textfield etc.
Dialog
• Dialog class has border and title.
• An instance of the Dialog class cannot exist
without an associated instance of the Frame
class.
Top-Level Containers: Frame, Dialog and Applet
• Each GUI program has a top-level container.
The commonly-used top-level containers in
AWT are Frame, Dialog and Applet
– A Frame provides the "main window" for the GUI
application, which has a title bar (containing an
icon, a title, the minimize, maximize/restore-down
and close buttons), an optional menu bar, and the
content display area.
Top-Level Containers: Frame, Dialog and Applet
• Each GUI program has a top-level container.
The commonly-used top-level containers in
AWT are Frame, Dialog and Applet
– An AWT Dialog is a "pop-up window" used for
interacting with the users.
– A Dialog has a title-bar (containing an icon, a title
and a close button) and a content display area, as
illustrated.
Top-Level Containers: Frame, Dialog and Applet
• Each GUI program has a top-level container.
The commonly-used top-level containers in
AWT are Frame, Dialog and Applet
– An AWT Applet (in package java.applet) is the top-
level container for an applet, which is a Java
program running inside a browser.
– Applet will be discussed in the later sessions.
AWT Packages
• The java.awt package contains the core AWT
graphics classes:
– GUI Component classes (such as Button, TextField,
and Label),
– GUI Container classes (such
as Frame, Panel, Dialog and ScrollPane),
– Layout managers (such
as FlowLayout, BorderLayout and GridLayout),
– Custom graphics classes (such
as Graphics, Color and Font).
AWT Packages
• The java.awt.event package supports event
handling:
– Event classes (such
as ActionEvent, MouseEvent, KeyEvent and WindowEv
ent),
– Event Listener Interfaces (such
as ActionListener, MouseListener, KeyListener and Win
dowListener),
– Event Listener Adapter classes (such
as MouseAdapter, KeyAdapter, and WindowAdapter).
AWT Example
• There are two ways to create a frame in
AWT.
– By extending Frame class (inheritance)
– By creating the object of Frame class
(association)
Commonly used Methods of
Component class
1. public void add(Component c)
2. public void setSize(int width,int height)
3. public void setLayout(LayoutManager m)
4. public void setVisible(boolean)
Commonly used Methods of
Component class
Simple example of AWT by inheritance
Simple example of AWT by association

creating
Frame by
creating
instance of
Frame class
The code in Listing 1 creates an empty frame
• The title of the frame ("Example 1") is set in
the call to the constructor. A frame is initially
invisible and must be made visible by invoking
its show() method.
AWT Controls
• Every user interface considers the following
three main aspects:
– UI elements
– Layouts
– Behavior
UI elements
• These are the core visual elements the user
eventually sees and interacts with.
• AWT provides a huge list of widely used and
common elements varying from basic to
complex
Layouts
• They define how UI elements should be
organized on the screen and provide a final
look and feel to the GUI (Graphical User
Interface).
• This part will be covered in Layout
Behavior
• These are events which occur when the user
interacts with UI elements.
• This part will be covered in Event Handling
Java AWT Hierarchy
Java Swing Hierarchy
Layout Managers
• The layout of the elements in a container is
handled by the layout manager associated
with the container.
• Relative positions of the elements are
specified, not their absolute coordinates.
• The positions and sizes of the element will be
automatically adjusted when the window is
resized
Layout Managers
Since the Component class defines the setSize()
and setLocation() methods, all Components can
be sized and positioned with those methods.
Problem:
the parameters provided to those methods are
defined in terms of pixels.
Pixel sizes may be different (depending on the
platform) so the use of those methods tends to
produce GUIs which will not display properly on all
platforms.
Layout Managers
Solution:
Layout Managers.
Layout managers are assigned to Containers.
When a Component is added to a Container, its
Layout Manager is consulted in order to
determine the size and placement of the
Component.
NOTE: If you use a Layout Manager, you can no longer
change the size and location of a Component through
the setSize and setLocation methods.
Layout Managers
There are several different LayoutManagers,
each of which sizes and positions its
Components based on an algorithm:
FlowLayout
BorderLayout
GridLayout

For Windows and Frames, the default


LayoutManager is BorderLayout.
For Panels, the default LayoutManager is
FlowLayout.
The Layout Manager Hierarchy
Flow Layout
• The algorithm used by the FlowLayout is
to lay out Components like words on a
page: Left to right, top to bottom
• It fits as many Components into a given
row before moving to the next row.
• If no room, a new row is started
Flow Layout
package AWT_Package;
import java.awt.*;

public class TestFlowLayout {


public static void main(String[] args){
Frame f = new Frame("TestFlowLayout");
f.setSize(200,200);
f.setLayout(new FlowLayout());

f.add(new Button("Button 1"));


f.add(new Button("Button 2"));
f.add(new Button("Button 3"));
f.add(new Button("Button 4"));
f.add(new Button("Button 5"));

f.setVisible(true);
}

}
Border Layout
The BorderLayout Manager breaks the
Container up into 5 regions (North, South,
East, West, and Center).
When Components are added, their region
is also specified:
Border Layout (cont)

The regions of the BorderLayout are defined as follows:

North

West Center East

South
Border Layout
import java.awt.*;
public class TestBorderLayout {
public static void main(String[] args) {
Frame f = new Frame("TesBorderLayout");
f.setSize(200,200);
f.add("North", new Button("North"));
f.add("South", new Button("South"));
f.add("East", new Button("East"));
f.add("West", new Button("West"));
f.add("Center", new Button("Center"));
f.setVisible(true);
}
}
Grid Layout
The GridLayout class divides the region
into a grid of equally sized rows and
columns.
Components are added left-to-right, top-to-
bottom.
The number of rows and columns is
specified in the constructor for the
LayoutManager.
Grid Layout
import java.awt.*;
public class TestGridLayout {
public static void main(String[] args) {
Frame f = new Frame("Test Grid Layout");
f.setSize(200,200);
GridLayout theLayout = new GridLayout(2,3);

f.setLayout(theLayout);
f.add(new Button("Button 1"));
f.add(new Button("Button 2"));
f.add(new Button("Button 3"));
f.add(new Button("Button 4"));
f.add(new Button("Button 5"));

f.setVisible(true);
}
}
What if I do not want a
LayoutManager?
LayoutManagers have
proved to be difficult
and frustrating to deal
with.
The LayoutManager
can be removed from a
Container by invoking
its setLayout method
with a null parameter.
What if I do not want a
LayoutManager? -Output
AWT Component Classes
AWT Component Classes
• AWT provides many ready-made and reusable
GUI components.
• The frequently-used are: Button, TextField,
Label, Checkbox, CheckboxGroup (radio
buttons), List, and Choice, as illustrated below.
AWT Component Classes
AWT GUI
Component: java.awt.Label
Adding Label Component
• Label is a passive control because it does not
create any event when accessed by the user.
• The label control is an object of Label.
• A label displays a single line of read-only text.
• However the text can be changed by the
application programmer but cannot be
changed by the end user in any way.
Adding Label Component
• A java.awt.Label provides a text description
message.
• Take note that System.out.println() prints to the
system console, not to the graphics screen.
• You could use a Label to label another
component (such as text field) or provide a text
description.
• Check the JDK API specification
for java.awt.Label.
Label constructors
• The Label class has three constructors:
–.
Field/Constants
• Following are the fields for
java.awt.Component class:
– static int CENTER -- Indicates that the label should be
centered.
– static int LEFT -- Indicates that the label should be left
justified.
– static int RIGHT -- Indicates that the label should be right
justified.

These three constants are defined for specifying the


alignment of the Label's text.
Public Methods

• The getText() and setText() methods can be


used to read and modify the Label's text.
Similarly,
the getAlignment() and setAlignment() method
s can be used to retrieve and modify the
alignment of the text.
Constructing a Component and Adding
the Component into a Container
• Three steps are necessary to create and place
a GUI component:
– Declare the component with an identifier (name);
– Construct the component by invoking an
appropriate constructor via the new operator;
– Identify the container (such as Frame or Panel)
designed to hold this component.
Constructing a Component and Adding
the Component into a Container
Label Example
Button class
• A Button is the most common
GUI control that
• lets you click on it do some
action.
• You might already have seen it a
lot of times, in OK and Cancel
buttons, for example.
Next Slide
AWT GUI Component: java.awt.Button
• A java.awt.Button is a GUI component that
triggers a certain programmed action upon
clicking.
java.awt.Button(Constructors)

• The Button class has two constructors.


• The first constructor creates a Button object
with the given label painted over the button.
• The second constructor creates a Button
object no label.
java.awt.Button(Public Methods)

• The getLabel() and setLabel() methods can be


used to read the current label and modify the
label of a button, respectively.
Creating an AWT Button
TextField class
• A TextField can contain a single
row text. It is
• mostly used for single line data.
You already have seen it in lot of
username fields and even in the
• subscribe field in the blog
sidebar.
It is a sub class of
TextComponent
java.awt.TextField
• A java.awt.TextField is single-line text box for
users to enter texts.
• (There is a multiple-line text box
called TextArea.)
• Hitting the "ENTER" key on a TextField object
triggers an action-event.
java.awt.TextField(Constructors)
java.awt.TextField(Public Methods)
TextField class
Checkbox class
• A checkbox allows user to check or
un check an
• option.
• Users can check multiple
checkboxes.
However, you can also use checkbox
as a radio
button (which restricts user to
select only one
out of various checkboxes) if several
checkboxes
Checkbox class
Checkbox class(contd…)
Choice class
• A Choice allows user to choose an item from a
list of similar items.
• It is a drop down menu also called as a combo
box (in swing) and only one item is visible
before drop down.
Choice
class
List class
• A List unlike a Choice allows
user to select multiple
items, however there is also
an option to restrict to a
single selection. But a list
looks different, all items are
visible in the List.
List class
Assignment
• Write java code using java.awt.* classes to
display the window in the next slide
Event Handling in Java
Java Event Handling
• Any action that user performs on a GUI
component must be listened and necessary action
should to be taken. For example, if a user clicks on
a Exit button, then we need to write code to exit
the program.
• So for this, we need to know that the user has
clicked the button.
• This process of knowing is called as listening and
the action done by the user is called an event.
• Writing the corresponding code for a user action
is called as Event handling.
Event and Listener (Java Event Handling)
• Changing the state of an object is known as an
event.
• In the delegation model, an event is an object
that describes a state change in a source.
• For example, click on button, dragging mouse
etc.
• The java.awt.event package provides many
event classes and Listener interfaces for event
handling.
Event Listeners
• A listener is an object that is notified when an
event occurs.
• It has two major requirements
– it must have been registered with one or more
sources to receive notifications about specific
types of events.
– it must implement methods to receive and
process these notifications.
Event Listeners
• Some of the activities that cause events to be
generated are pressing a button, entering a
character via the keyboard, selecting an item
in a list, and clicking the mouse
• Events may also occur that are not directly
caused by interactions with a user interface.
• For example, an event may be generated
when a timer expires, a counter exceeds a
value, a software or hardware failure occurs,
or an operation is completed.
Event Sources
• A source is an object that generates an event.
• This occurs when the internal state of that
object changes in some way.
• Sources may generate more than one type of
event.
• A source must register listeners in order for
the listeners to receive notifications about a
specific type of event. Each type of event has
its own registration method. Here is the
Event Sources
• Each type of event has its own registration
method. Here is the general form:
public void add TypeListener(TypeListener el)
• Here, Type is the name of the event, and el is a
reference to the event listener.
– For example, the method that registers a keyboard
event listener is called addKeyListener( ).
• The method that registers a mouse motion
listener is called addMouseMotionListener( ).
• When an event occurs, all registered listeners are
notified and receive a copy of the event object
Event Listeners
• The methods that receive and process events
are defined in a set of interfaces found in
java.awt.event
AWT ActionListener Interface
References

• Java Programming by Joyce Farrel


• Introduction to Java Programming 8th Edition
by Y. Daniel Liang
• http://www.javatpoint.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy