AWT notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

AWT (Abstract Window Toolkit)

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User


Interface (GUI) or windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are


displayed according to the view of operating system. AWT is heavy weight
i.e. its components are using the resources of underlying operating
system (OS).

The java.awt package provides classes for AWT API such


as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in
simple and easy steps.

Points about Java AWT components


i. Components of AWT are heavy and platform dependent
ii. AWT has less control as the result can differ because of
components are platform dependent.

Why AWT is Platform Independent?


The Java AWT utilizes the native platform subroutine to create
API components such as TextField, CheckBox, and buttons. This
results in a different visual format for these components on
different platforms such as Windows, MAC OS, and Unix. The
reason for this is that each platform has a distinct view of its
native components. AWT directly calls this native subroutine to
create the components, resulting in an AWT application
resembling a Windows application on Windows OS, and a Mac
application on the MAC OS. In simpler terms, the AWT
application’s appearance adapts to the platform it is running on.
AWT is platform independent even after the AWT components
are platform dependent because of the points mentioned below:

1. JVM (Java Virtual Machine):


As Java Virtual Machine is platform dependent
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact
with AWT through Abstract API which are platform independent.
Abstract API allows Java to isolate platform-specific details,
making code portable across different systems.

3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally
platform-independent. Because of this, it ensures that AWT
functionality remains consistent across different environments.
Java AWT Hierarchy
 Components: AWT provides various components such
as buttons, labels, text fields, checkboxes, etc used for
creating GUI elements for Java Applications.
 Containers: AWT provides containers like panels,
frames, and dialogues to organize and group components
in the Application.
 Layout Managers: Layout Managers are responsible for
arranging data in the containers some of the layout
managers are BorderLayout, FlowLayout, etc.
 Event Handling: AWT allows the user to handle the
events like mouse clicks, key presses, etc. using event
listeners and adapters.
 Graphics and Drawing: It is the feature of AWT that
helps to draw shapes, insert images and write text in the
components of a Java Application.
Note: Container can be added inside another container as it is
type of component.

Types of Containers in Java AWT


There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents
a graphical window or dialog box. The Window class
extends the Container class, which means it can contain
other components, such as buttons, labels, and text
fields.
2. Panel: Panel is a container class in Java. It is a
lightweight container that can be used for grouping other
components together within a window or a frame.
3. Frame: The Frame is the container that contains the title
bar and border and can have menu bars.
4. Dialog: A dialog box is a temporary window an
application creates to retrieve user input.
1. Java AWT Label
Syntax of AWT Label
public class Label extends Component implements Accessible
AWT Label Class Constructors
There are three types of Java AWT Label Class
1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified
alignment

2. Java AWT Button


AWT Button is a control component with a label that generates
an event when clicked on. Button Class is used for creating a
labeled button that is platform-independent.
Syntax of AWT Button
public class Button extends Component implements Accessible
Java AWT Button Class Constructors
There are two types of Button class constructors as mentioned
below:
1. Button( ):
Creates a Button with no label i.e. showing an empty box as a
button.
2. Button(String str):
Creates a Button with String str as a label. For example if
str=”Click Here” button with show click here as the value.

3. Java AWT TextField


Syntax of AWT TextField:
public class TextField extends TextComponent
TextField Class constructors
There are TextField class constructors are mentioned below:
1. TextField():
Constructs a TextField component.
2. TextField(String text):
Constructs a new text field initialized with the given string str to
be displayed.
3. TextField(int col):
Creates a new text field(empty) with the given number of
columns (col).
4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the
given number of columns (col).

4. Java AWT Checkbox


Syntax of AWT Checkbox:
public class Checkbox extends Component implements ItemSelect
able, Accessible
Checkbox Class Constructors
There are certain constructors in the AWT Checkbox class as
mentioned below:
1. Checkbox():
Creates a checkbox with no label.
2. Checkbox(String str):
Creates a checkbox with a str label.
3. Checkbox(String str, boolean state, CheckboxGroup
group):
Creates a checkbox with the str label, and sets the state in the
mentioned group.

5. Java AWT CheckboxGroup


CheckboxGroup Class is used to group together a set of
Checkbox.
Syntax of AWT CheckboxGroup:
public class CheckboxGroup extends Object implements Serializ
able
Note: CheckboxGroup enables the use of radio buttons in AWT.

6. Java AWT Choice


The object of the Choice class is used to show a popup menu of
choices.
Syntax of AWT Choice:
public class Choice extends Component implements ItemSelectab
le, Accessible
AWT Choice Class constructor
Choice(): It creates a new choice menu.
7. Java AWT List
The object of the AWT List class represents a list of text items.
Syntax of Java AWT List:
public class List extends Component implements ItemSelectable
, Accessible
AWT List Class Constructors
The List of class constructors is defined below:
1. List():
Creates a new list.
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of
rows.

8. Java AWT Canvas


Syntax of AWT Canvas:
public class Canvas extends Component implements Accessible
Canvas Class Constructors
1. Canvas():
Creates new Canvas.
2. Canvas(GraphicConfiguration config):
It creates a new Canvas with the given Graphic configuration.

9. AWT Scrollbar
Syntax of AWT Scrollbar:
public class Scrollbar extends Component implements Adjustabl
e, Accessible
Java AWT Scrollbar Class Constructors
There are three constructor classes in Java mentioned below:
1.Scrollbar():
It Creates a new vertical Scrollbar in the Application.
2.Scrollbar(int-orientation):
Creates a new vertical Scrollbar with the given orientation.
3. Scrollbar(int orientation, int value, int visible, int mini,
int maxi):
Creates a new scrollbar with the orientation mentioned with
value as the default value and [mini, maxi] as the lower and
higher limit.
10. Java AWT MenuItem & Menu
MenuItem class adds a simple labeled menu item on the menu.
The MenuItem class allows you to create individual items that
can be added to menus. And Menu is a component used to
create a dropdown menu that can contain a list of MenuItem
components.
Syntax of Java AWT MenuItem
public class MenuItem extends MenuComponent implements Access
ible
Syntax of Java AWT Menu
public class Menu extends MenuItem implements MenuContainer,
Accessible
Java AWT PopupMenu is a component that is used for
dynamically popping up a menu that appears when the user
right-clicks or performs any other action on a component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer,
Accessible

12. Java AWT Panel


Java AWT Panel is a container class used to hold and organize
graphical components in a Java Application.
Syntax of Java AWT Panel:
public class Panel extends Container implements Accessible

13. Java AWT Toolkit


Java AWT Toolkit class provides us with a platform-independent
way to access various system resources and functionalities.
Subclasses of Toolkit are used to bind various components.
Syntax of Java AWT Toolkit
public abstract class Toolkit extends Object

Developing AWT Method 1


package myfirst2;

import java.awt.*;

public class MyFirst2


{
static int count=0;

public static void main(String[] args)


{
Frame f=new Frame();
f.setTitle("My First Window App");
Button b=new Button("Click Me");
f.add(b);
TextField tf=new TextField(20);
f.add(tf);

b.addActionListener((e)->tf.setText("Clicked "+count++));

f.setLayout(new FlowLayout());
f.setSize(500,500);
f.setVisible(true);

}}

Developing AWT Method 2


package firstapp;
import java.awt.*;

public class FirstApp extends Frame


{
Label l;
TextField tf;
Button b;

public FirstApp()
{
super("My App");

setLayout(new FlowLayout());

l=new Label("Name");
tf=new TextField(20);
b=new Button("OK");

add(l);
add(tf);
add(b);

}
public static void main(String[] args)
{
FirstApp f=new FirstApp();
f.setSize(400,400);
f.setVisible(true);
}
}

Event Handling Components – Java


AWT
1. Java ActionListener
Java ActionListner is a interface which responds to the actions
performed by the components like buttons, menu items ,etc.
Syntax of Java ActionListener:
public class ActionListenerExample Implements ActionListener
There is only methods associated with ActionListner class that is
actionPerformed().
Syntax of actionPerformed() method:
public abstract void actionPerformed(ActionEvent e);

2. Java MouseListener
Java MouseListner is a interface that responds to the actions
performed by mouse events generated by the user. Example:
mouse clicks , mouse movements, etc.
There are 5 Methods associated with MouseListner:
1. mouseClicked(MouseEvent e):
Responds to mouse buttons when clicked on a component in the
Application.
2. mousePressed(MouseEvent e):
Responds to mouse button is Pressed on a component in the
Application.
3. mouseReleased(MouseEvent e):
Responds to Mouse button released after being pressed over a
component in the Application.
4. mouseEntered(MouseEvent e):
Responds to the situation when a Mouse cursor enters the
bounds of a component in an Application.
5. mouseExited(MouseEvent e):
Responds to the situation when a Mouse cursor exits a
component’s bounds.
3. Java MouseMotionListener
Java MouseMotionListner is a interface which is notified when
mouse is moved or dragged.
It contains two Methods mentioned below:
1. mouseDragged(MouseEvent e):
Responds when the mouse is dragged with mouse button clicked
over a component in Application.
2. mouseMoved(MouseEvent e):
Responds when the mouse is moved over a component in
Application.

4. Java ItemListener
Java ItemListner is an interface which handles events related to
item selection and deselection those that occur with checkboxes,
radio buttons, etc. There is only one Method associated with
ItemListner that is itemStateChanged(). This method provides
information about the event, i.e. source of the event and the
changed state.
Syntax of itemStateChanged() method:
itemStateChanged(ItemEvent e)

5. Java KeyListener
Java KeyListner is an interface in Java notified whenever you
change the state of key or can be said for key related events.
Syntax of KeyListener:
public interface KeyListener extends EventListener
There are three methods associated with KeyListner as
mentioned below:
1. keyPressed (KeyEvent e):
Responds to the event when key is pressed.
2. keyReleased (KeyEvent e):
Responds to the event when the key is released.
3. keyTyped (KeyEvent e):
Responds to the key has been typed.
6. Java WindowListener
Java WindowListener is a interface used for handling events
related to window actions. Events like opening , closing,
minimizing, etc are handled using WindowListener.
Syntax of WindowListener
public interface WindowListener extends EventListener
There are seven methods associated with WindowListener as
mentioned below:
1. windowActivated (WindowEvent e):
Responds when window is first opened
2. windowClosed (WindowEvent e):
Responds when the user attempts to close the window
3. windowClosing (WindowEvent e):
Responds after a window has been closed
4. windowDeactivated (WindowEvent e):
Responds when a window is minimized
5. windowDeiconified (WindowEvent e):
Responds when a window is restored from a minimized state
6. windowIconified (WindowEvent e):
Responds when a window is activated
7. windowOpened (WindowEvent e):
Responds when a window loses focus

7. Java Adapter classes


Java adapter classes provide the default implementation of
listener interfaces.

8. Close AWT Window


At the end we will need to Close AWT Window, So to perform this
task we will use dispose() method. This method releases the
resources associated with the window and also removes it from
the screen.

Delegation Event Model in Java


The Delegation Event model is defined to handle events in
GUI programming languages. The GUI stands for Graphical User Interface,
where a user graphically/visually interacts with the system.

The GUI programming is inherently event-driven; whenever a user


initiates an activity such as a mouse activity, clicks, scrolling, etc., each is
known as an event that is mapped to a code to respond to functionality to
the user. This is known as event handling.

In this section, we will discuss event processing and how to implement the
delegation event model in Java. We will also discuss the different
components of an Event Model.
Event Processing in Java
Java support event processing since Java 1.0. It provides support for AWT (
Abstract Window Toolkit), which is an API used to develop the Desktop
application. In Java 1.0, the AWT was based on inheritance. To catch and
process GUI events for a program, it should hold subclass GUI components
and override action() or handleEvent() methods. The below image
demonstrates the event processing.

But, the modern approach for event processing is based on the Delegation
Model. It defines a standard and compatible mechanism to generate and
process events. In this model, a source generates an event and forwards it
to one or more listeners. The listener waits until it receives an event. Once
it receives the event, it is processed by the listener and returns it. The UI
elements are able to delegate the processing of an event to a separate
function.

The key advantage of the Delegation Event Model is that the application
logic is completely separated from the interface logic.

In this model, the listener must be connected with a source to receive the
event notifications. Thus, the events will only be received by the listeners
who wish to receive them. So, this approach is more convenient than the
inheritance-based event model (in Java 1.0).
In the older model, an event was propagated up the containment until a
component was handled. This needed components to receive events that
were not processed, and it took lots of time. The Delegation Event model
overcame this issue.

Basically, an Event Model is based on the following three components:

o Events
o Events Sources
o Events Listeners

Events
The Events are the objects that define state change in a source. An event
can be generated as a reaction of a user while interacting with GUI
elements. Some of the event generation activities are moving the mouse
pointer, clicking on a button, pressing the keyboard key, selecting an item
from the list, and so on. We can also consider many other user operations
as events.

Event Sources
A source is an object that causes and generates an event. It generates an
event when the internal state of the object is changed. The sources are
allowed to generate several different types of events.

A source must register a listener to receive notifications for a specific


event. Each event contains its registration method. Below is an example:

1. public void addTypeListener (TypeListener e1)

From the above syntax, the Type is the name of the event, and e1 is a
reference to the event listener. For example, for a keyboard event
listener, the method will be called as addKeyListener(). For the mouse
event listener, the method will be called as addMouseMotionListener().
When an event is triggered using the respected source, all the events will
be notified to registered listeners and receive the event object. This
process is known as event multicasting. In few cases, the event
notification will only be sent to listeners that register to receive them.

Some listeners allow only one listener to register. Below is an example:

1. public void addTypeListener(TypeListener e2) throws java.util.Too


ManyListenersException
From the above syntax, the Type is the name of the event, and e2 is the
event listener's reference. When the specified event occurs, it will be
notified to the registered listener. This process is known
as unicasting events.

A source should contain a method that unregisters a specific type of event


from the listener if not needed. Below is an example of the method that
will remove the event from the listener.

1. public void removeTypeListener(TypeListener e2?)

From the above syntax, the Type is an event name, and e2 is the
reference of the listener. For example, to remove the keyboard listener,
the removeKeyListener() method will be called.

The source provides the methods to add or remove listeners that generate
the events. For example, the Component class contains the methods to
operate on the different types of events, such as adding or removing them
from the listener.

Event Listeners
An event listener is an object that is invoked when an event triggers. The
listeners require two things; first, it must be registered with a source;
however, it can be registered with several resources to receive notification
about the events. Second, it must implement the methods to receive and
process the received notifications.

The methods that deal with the events are defined in a set of interfaces.
These interfaces can be found in the java.awt.event package.

For example, the MouseMotionListener interface provides two methods


when the mouse is dragged and moved. Any object can receive and
process these events if it implements the MouseMotionListener interface.

Types of Events
The events are categories into the following two categories:

The Foreground Events:

The foreground events are those events that require direct interaction of
the user. These types of events are generated as a result of user
interaction with the GUI component. For example, clicking on a button,
mouse movement, pressing a keyboard key, selecting an option from the
list, etc.

The Background Events :


The Background events are those events that result from the interaction
of the end-user. For example, an Operating system interrupts system
failure (Hardware or Software).

To handle these events, we need an event handling mechanism that


provides control over the events and responses.

The Delegation Model


The Delegation Model is available in Java since Java 1.1. it provides a new
delegation-based event model using AWT to resolve the event problems. It
provides a convenient mechanism to support complex Java programs.

Design Goals
The design goals of the event delegation model are as following:

o It is easy to learn and implement


o It supports a clean separation between application and GUI code.
o It provides robust event handling program code which is less error-prone
(strong compile-time checking)
o It is Flexible, can enable different types of application models for event
flow and propagation.
o It enables run-time discovery of both the component-generated events as
well as observable events.
o It provides support for the backward binary compatibility with the previous
model.

Let's implement it with an example:

Java Program to Implement the Event Deligation Model


The below is a Java program to handle events implementing the event
deligation model:

TestApp.java:

1. import java.awt.*;
2. import java.awt.event.*;
3.
4. public class TestApp {
5. public void search() {
6. // For searching
7. System.out.println("Searching...");
8. }
9. public void sort() {
10. // for sorting
11. System.out.println("Sorting....");
12. }
13.
14. static public void main(String args[]) {
15. TestApp app = new TestApp();
16. GUI gui = new GUI(app);
17. }
18.}
19.
20.class Command implements ActionListener {
21. static final int SEARCH = 0;
22. static final int SORT = 1;
23. int id;
24. TestApp app;
25.
26. public Command(int id, TestApp app) {
27. this.id = id;
28. this.app = app;
29. }
30.
31. public void actionPerformed(ActionEvent e) {
32. switch(id) {
33. case SEARCH:
34. app.search();
35. break;
36. case SORT:
37. app.sort();
38. break;
39. }
40. }
41. }
42.
43. class GUI {
44.
45. public GUI(TestApp app) {
46. Frame f = new Frame();
47. f.setLayout(new FlowLayout());
48.
49. Command searchCmd = new Command(Command.SEAR
CH, app);
50. Command sortCmd = new Command(Command.SORT, app);
51.
52. Button b;
53. f.add(b = new Button("Search"));
54. b.addActionListener(searchCmd);
55. f.add(b = new Button("Sort"));
56. b.addActionListener(sortCmd);
57.
58. List l;
59. f.add(l = new List());
60. l.add("Alphabetical");
61. l.add("Chronological");
62. l.addActionListener(sortCmd);
63. f.pack();
64.
65. f.show();
66. }
67. }

You might also like