Java AWT and Event Handling Notes
Java Abstract Window Toolkit (AWT)
Introduction
AWT is a set of classes and APIs for creating GUIs in Java.
It is one of the oldest GUI toolkits in Java.
Event handling is essential in GUI programming. Events are actions like mouse clicks or key presses.
Java AWT
AWT stands for Abstract Window Toolkit, an API for creating GUIs in Java.
It enables Java programmers to develop window-based applications.
AWT provides components like buttons, labels, and checkboxes.
AWT components use OS resources, making them platform-dependent (look and feel changes based on the OS).
Classes for AWT are in the
java.awtpackage.
Hierarchy
Component Class:
At the top of the AWT hierarchy. An abstract class with properties for components visible on the screen.
Contains information about foreground, background, and text colors.
Container:
A component that can hold other components (buttons, text fields, labels, etc.).
A subclass of the Component class.
Panel:
A container to hold components.
Does not have a title bar, menu bar, or border.
Window:
A container without a border or menu bar; creates a top-level view.
Requires a frame, dialog, or another window.
Frame:
A subclass of Window.
A container with components like buttons, text fields, labels, etc.
AWT applications are often created using the frame container.
Platform Independence
AWT achieves platform independence by calling native platform (OS) subroutines to create API components (e.g., TextField, CheckBox, Button).
An AWT GUI with components will have a different look and feel on different platforms (Windows, macOS, Unix) because AWT directly calls the native subroutines.
Useful Methods of Component Class
public void add(Component c): Inserts a component on this component.public void setSize(int width, int height): Sets the size (width and height) of the component.public void setLayout(LayoutManager m): Defines the layout manager for the component.public void setVisible(boolean status): Changes the visibility of the component; default is false.
Example
A simple example: Creating a button within a window frame.
import java.awt.*;
public class AwtProgram1 {
public AwtProgram1() {
Frame f = new Frame();
Button btn = new Button("Hello World");
btn.setBounds(80, 80, 100, 50);
f.add(btn); // adding a new Button.
f.setSize(300, 250); // setting size.
f.setTitle("JavaTPoint"); // setting title.
f.setLayout(null); // set default layout for frame.
f.setVisible(true); // set frame visibility true.
}
public static void main(String[] args) {
// TODO Auto-generated method stub
AwtProgram1 awt = new AwtProgram1(); // creating a frame.
}
}
Another example: Creating a user form with text fields and labels.
import java.awt.*;
public class AwtApp extends Frame {
AwtApp() {
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);
Label lastName = new Label("Last Name");
lastName.setBounds(20, 80, 80, 20);
Label dob = new Label("Date of Birth");
dob.setBounds(20, 110, 80, 20);
TextField firstNameTF = new TextField();
firstNameTF.setBounds(120, 50, 100, 20);
TextField lastNameTF = new TextField();
lastNameTF.setBounds(120, 80, 100, 20);
TextField dobTF = new TextField();
dobTF.setBounds(120, 110, 100, 20);
Button sbmt = new Button("Submit");
sbmt.setBounds(20, 160, 100, 30);
Button reset = new Button("Reset");
reset.setBounds(120, 160, 100, 30);
add(firstName);
add(lastName);
add(dob);
add(firstNameTF);
add(lastNameTF);
add(dobTF);
add(sbmt);
add(reset);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
AwtApp awt = new AwtApp();
}
}
Java Event Listeners and Handling
Changing the state of an object is known as an event (e.g., button click, mouse dragging).
The
java.awt.eventpackage provides event classes and Listener interfaces for event handling.
Event Classes and Listener Interfaces
Event Class | Listener Interfaces |
|---|---|
ActionEvent | ActionListener |
MouseEvent | MouseListener, MouseMotionListener |
MouseWheelEvent | MouseWheelListener |
KeyEvent | KeyListener |
ItemEvent | ItemListener |
TextEvent | TextListener |
AdjustmentEvent | AdjustmentListener |
WindowEvent | WindowListener |
ComponentEvent | ComponentListener |
ContainerEvent | ContainerListener |
FocusEvent | FocusListener |
Steps to Perform Event Handling
Register the component with the Listener:
Classes provide registration methods for associating components with listeners.
Examples:
Button:public void addActionListener(ActionListener a){}MenuItem:public void addActionListener(ActionListener a){}TextField:public void addActionListener(ActionListener a){}public void addTextListener(TextListener a){}
TextArea:public void addTextListener(TextListener a){}Checkbox:public void addItemListener(ItemListener a){}Choice:public void addItemListener(ItemListener a){}List:public void addActionListener(ActionListener a){}public void addItemListener(ItemListener a){}
Write Event Handling Code:
Event handling code can be placed in one of three locations:
Within the class
In another class
Using an anonymous class
Examples of Event Handling
Within Class:
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener {
TextField tf;
AEvent() {
// create components
tf = new TextField();
tf.setBounds(60, 50, 170, 20);
Button b = new Button("click me");
b.setBounds(100, 120, 80, 30);
// register listener
b.addActionListener(this); // passing current instance
// add components and set size, layout and visibility
add(b);add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
tf.setText("Welcome");
}
public static void main(String args[]) {
new AEvent();
}
}
The
setBounds(int xaxis, int yaxis, int width, int height)method sets the position of the component.
Outer Class:
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame {
TextField tf;
AEvent2() {
// create components
tf = new TextField();
tf.setBounds(60, 50, 170, 20);
Button b = new Button("click me");
b.setBounds(100, 120, 80, 30);
//register listener
Outer o = new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]) {
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener {
AEvent2 obj;
Outer(AEvent2 obj) {
this.obj = obj;
}
public void actionPerformed(ActionEvent e) {
obj.tf.setText("welcome");
}
}
Anonymous Class:
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame {
TextField tf;
AEvent3() {
tf = new TextField();
tf.setBounds(60, 50, 170, 20);
Button b = new Button("click me");
b.setBounds(50, 120, 80, 30);
b.addActionListener(new ActionListener() {
public void actionPerformed() {
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]) {
new AEvent3();
}
}
Java ActionListener
The
ActionListenerinterface is notified whenever a button or menu item is clicked.It is found in the
java.awt.eventpackage.It contains only one method:
actionPerformed().actionPerformed()is invoked automatically when the registered component is clicked.Syntax:
public abstract void actionPerformed(ActionEvent e);
How to write ActionListener
Implement the
ActionListenerinterface in the class:public class ActionListenerExample implements ActionListener
Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
Override the
actionPerformed()method:java public void actionPerformed(ActionEvent e) { //Write the code here }
ActionListener Examples
On Button Click:
import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener {
public static void main(String[] args) {
Frame f = new Frame("ActionListener Example");
final TextField tf = new TextField();
tf.setBounds(50, 50, 150, 20);
Button b = new Button("Click Here");
b.setBounds(50, 100, 60, 30);
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e) {
tf.setText("Welcome to Javatpoint.");
}
}
Using Anonymous Class:
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tf.setText("Welcome to Javatpoint.");
}
});
Full Code:
import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample {
public static void main(String[] args) {
Frame f = new Frame("ActionListener Example");
final TextField tf = new TextField();
tf.setBounds(50, 50, 150, 20);
Button b = new Button("Click Here");
b.setBounds(50, 100, 60, 30);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
}
Java MouseListener
The
MouseListeneris notified whenever the state of the mouse changes.It is found in the
java.awt.eventpackage.It has five methods:
Methods of MouseListener Interface
public abstract void mouseClicked(MouseEvent e);public abstract void mouseEntered(MouseEvent e);public abstract void mouseExited(MouseEvent e);public abstract void mousePressed(MouseEvent e);public abstract void mouseReleased(MouseEvent e);
MouseListener Example
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener {
Label l;
MouseListenerExample() {
addMouseListener(this);
l = new Label();
l.setBounds(20, 50, 100, 20);
add(l);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Java MouseMotionListener
The
MouseMotionListeneris notified whenever the mouse is moved or dragged.It is found in the
java.awt.eventpackage.It has two methods:
Methods of MouseMotionListener Interface
public abstract void mouseDragged(MouseEvent e);public abstract void mouseMoved(MouseEvent e);
MouseMotionListener Example
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener {
MouseMotionListenerExample() {
addMouseMotionListener(this);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g = getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(), e.getY(), 20, 20);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new MouseMotionListenerExample();
}
}
Java ItemListener
The
ItemListeneris notified whenever a checkbox is clicked.It is found in the
java.awt.eventpackage.It has one method:
itemStateChanged().
itemStateChanged() Method
Invoked automatically when the registered checkbox component is clicked or unclicked.
Syntax:
public abstract void itemStateChanged(ItemEvent e);
ItemListener Example
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener {
Checkbox checkBox1, checkBox2;
Label label;
ItemListenerExample() {
Frame f = new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400, 100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100, 100, 50, 50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100, 150, 50, 50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == checkBox1)
label.setText("C++ Checkbox: "
+ (e.getStateChange() == 1 ? "checked" : "unchecked"));
if (e.getSource() == checkBox2)
label.setText("Java Checkbox: "
+ (e.getStateChange() == 1 ? "checked" : "unchecked"));
}
public static void main(String args[]) {
new ItemListenerExample();
}
}
Java KeyListener
The
KeyListeneris notified whenever the state of a key changes.It is found in the
java.awt.eventpackage.It has three methods.
Interface Declaration
public interface KeyListener extends EventListener
Methods of KeyListener Interface
Sr. no. | Method name | Description |
|---|---|---|
1. |
| Invoked when a key has been pressed. |
2. |
| Invoked when a key has been released. |
3. |
| Invoked when a key has been typed. |
Methods inherited
This interface inherits methods from the following interface:
java.awt.EventListener
KeyListener Example: Count Words & Characters
The example counts words and characters from a TextArea using the
keyReleased()method.
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample2 extends Frame implements KeyListener {
// object of Label and TextArea
Label l;
TextArea area;
// class constructor
KeyListenerExample2() {
// creating the label
l = new Label();
// setting the location of label
l.setBounds(20, 50, 200, 20);
// creating the text area
area = new TextArea();
// setting location of text area
area.setBounds(20, 80, 300, 300);
// adding KeyListener to the text area
area.addKeyListener(this);
// adding label and text area to frame
add(l);add(area);
// setting size, layout and visibility of frame
setSize(400, 400);
setLayout(null);
setVisible(true);
}
// even if we do not define the interface methods, we need to override them
public void keyPressed(KeyEvent e) {}
// overriding the keyReleased() method of KeyListener interface
public void keyReleased(KeyEvent e) {
// defining a string which is fetched by the getText() method of TextArea class
String text = area.getText();
// splitting the string in words
String words[] = text.split("\\s");
// printing the number of words and characters of the string
l.setText("Words: " + words.length + " Characters:" + text.length());
}
public void keyTyped(KeyEvent e) {}
// main method
public static void main(String[] args) {
new KeyListenerExample2();
}
}