A GUI (Graphical User Interface) allows users to interact with programs using buttons, menus, windows, text fields, etc., instead of typing commands.
👉 Java provides GUI through:
| Feature | AWT | Swing |
|---|---|---|
| Type | Heavyweight | Lightweight |
| Components | Platform dependent | Platform independent |
| Look | Native OS look | Custom look |
| Package | java.awt |
javax.swing |
Common components used in GUI:
import javax.swing.*;
public class Demo {
public static void main(String[] args) {
JFrame f = new JFrame("My Window");
JButton b = new JButton("Click Me");
b.setBounds(100, 100, 120, 40);
f.add(b);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
}
An event is an action like:
Event handling is the process of responding to these events.
Java uses Delegation Event Model, which includes:
📊 Event Handling Diagram:
Some important event classes:
ActionEvent → Button clickMouseEvent → Mouse actionsKeyEvent → Keyboard inputWindowEvent → Window actions| Listener | Purpose |
|---|---|
| ActionListener | Button click |
| MouseListener | Mouse events |
| KeyListener | Keyboard input |
| WindowListener | Window events |
import javax.swing.*;
import java.awt.event.*;
public class EventDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Event Example");
JButton b = new JButton("Click");
b.setBounds(100, 100, 100, 40);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
});
f.add(b);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
}
addActionListener()actionPerformed() method handles clickAdapter classes provide default implementations of listener interfaces.
👉 Useful when:
import java.awt.event.*;
class MyWindow extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
import javax.swing.*;
import java.awt.event.*;
public class InnerDemo {
public static void main(String[] args) {
JFrame f = new JFrame();
JButton b = new JButton("Click");
b.setBounds(100, 100, 100, 40);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Handled using inner class");
}
});
f.add(b);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
}
Controls arrangement of components.
Open this section to load past papers