Unit 4: AWT, event handling and I/O
Programming in Java notes · PTU syllabus (BSIT502/BSBC502)
On this page
Unit summary
Desktop applications need windows, controls and responses to user actions, and programs need to read and write files. This unit covers AWT containers, components and layouts, the event delegation model, ActionListener, MouseListener, WindowListener and KeyListener, and file I/O with byte streams, character streams and random access files.
After this unit you can
- Build GUIs with AWT containers, components and layouts
- Handle events using the delegation model and listeners
- Read and write files with byte and character streams
- Use random access files
PTU syllabus topics
- Java AWT package containers
- UI components and layouts
- event delegation approach
- ActionListener/MouseListener/WindowListener/KeyListener
- I/O file handling — input/output streams
- FileInputStream/FileOutputStream
- reader/writer streams
- random access files
- 1User acts
Clicks a button
- 2Source creates an event object
ActionEvent
- 3Event sent to registered listener
- 4Listener method runs
actionPerformed()
Topic 1
AWT containers
Container
Holds other components
Window and Frame
Top-level window with title bar
Dialog
Pop-up window
Panel
Container without a title bar; groups components
Basic components
Button, Label, TextField, TextArea, Checkbox, Choice, List, Scrollbar
- AWT (Abstract Window Toolkit) uses native, heavyweight components; Swing (JFrame, JButton) adds lightweight, richer components and is preferred for new desktop code.
Topic 2
UI components and layouts
FlowLayout
Left to right, wrapping to the next row
Panel and Applet
BorderLayout
Five regions: North, South, East, West, Center
Frame and Window
GridLayout
Equal-sized cells in rows and columns
—
CardLayout
Stack of cards, one visible at a time
—
GridBagLayout
Flexible grid with constraints
—
Topic 3
The event delegation model
- 1Source
Component generates an event — button click
- 2Event object
ActionEvent carries details
- 3Registration
Listener registered with addActionListener
- 4Listener
Receives the event and runs the handler method
- ActionListener
- actionPerformed(ActionEvent) — buttons, menu items, Enter in a text field
- MouseListener
- mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited
- KeyListener
- keyPressed, keyReleased, keyTyped
- WindowListener
- windowClosing, windowOpened, windowClosed, windowActivated and others
- Adapter classes
- MouseAdapter, WindowAdapter — override only needed methods
Topic 4
Event handling program
javaimport java.awt.*;
import java.awt.event.*;
public class AddFrame extends Frame implements ActionListener {
TextField t1 = new TextField(10), t2 = new TextField(10);
Label result = new Label("Result: ");
Button add = new Button("Add");
AddFrame() {
super("Adder");
setLayout(new FlowLayout());
add(new Label("A")); add(t1); add(new Label("B")); add(t2); add(add); add(result);
add.addActionListener(this); // ActionListener
addMouseListener(new MouseAdapter() { // MouseListener via adapter
public void mouseClicked(MouseEvent e) { setTitle("Clicked at " + e.getX() + "," + e.getY()); }
});
t2.addKeyListener(new KeyAdapter() { // KeyListener
public void keyTyped(KeyEvent e) { if (!Character.isDigit(e.getKeyChar())) e.consume(); }
});
addWindowListener(new WindowAdapter() { // WindowListener
public void windowClosing(WindowEvent e) { dispose(); }
});
setSize(420, 120); setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int s = Integer.parseInt(t1.getText()) + Integer.parseInt(t2.getText());
result.setText("Result: " + s);
}
public static void main(String[] args) { new AddFrame(); }
}Topic 5
I/O streams
Unit
8-bit bytes
16-bit Unicode characters
Base classes
InputStream and OutputStream
Reader and Writer
File classes
FileInputStream, FileOutputStream
FileReader, FileWriter
Buffered
BufferedInputStream, BufferedOutputStream
BufferedReader, BufferedWriter
Used for
Images, audio, binary data
Text files
- Standard streams: System.in (InputStream), System.out and System.err (PrintStream). The File class gives file information (exists, length, delete, list).
Topic 6
FileInputStream and FileOutputStream
javaimport java.io.*;
// copy any file byte by byte
try (FileInputStream in = new FileInputStream("photo.jpg");
FileOutputStream out = new FileOutputStream("copy.jpg")) {
int b;
while ((b = in.read()) != -1) out.write(b);
} catch (IOException e) { System.out.println(e.getMessage()); }Topic 7
Reader and writer streams
java// write and read a text file line by line
try (BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt", true))) { // append
bw.write("101,Aman,82"); bw.newLine();
}
try (BufferedReader br = new BufferedReader(new FileReader("students.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] f = line.split(",");
System.out.println(f[1] + " scored " + f[2]);
}
}Topic 8
Random access files
- RandomAccessFile reads and writes at any position using a file pointer — modes "r" and "rw"; methods seek(), getFilePointer(), length(), readInt(), writeInt(), readUTF(), writeUTF().
javatry (RandomAccessFile raf = new RandomAccessFile("marks.dat", "rw")) {
for (int m : new int[]{78, 85, 90, 66}) raf.writeInt(m); // each int = 4 bytes
raf.seek(2 * 4); // jump to the third record
System.out.println(raf.readInt()); // 90
raf.seek(2 * 4);
raf.writeInt(95); // update in place
}Example
Fixed-length records make random access easy: record n starts at byte n × recordSize.
Key terms
- AWT
- Java's original GUI toolkit
- Layout manager
- Object that arranges components in a container
- Event delegation model
- Events sent from a source to registered listeners
- Adapter class
- Class with empty listener methods to override selectively
- RandomAccessFile
- Class allowing reading and writing at any file position
Quick revision
- Component, Container, Frame, Panel; AWT vs Swing.
- FlowLayout, BorderLayout, GridLayout, CardLayout, GridBagLayout.
- Source, event, listener; Action, Mouse, Key, Window listeners; adapters.
- Byte vs character streams; FileInputStream, FileOutputStream, FileReader, FileWriter, buffered streams.
- RandomAccessFile: seek, read, write.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.Distinguish Frame and Panel.
- Q2.Which is the default layout of a Frame?
- Q3.What is the event delegation model?
- Q4.What is an adapter class?
- Q5.Distinguish byte and character streams.
- Q6.What does seek() do?
Long-answer questions
- Q1.Explain AWT containers, components and layout managers.
- Q2.Explain event handling with a program using ActionListener and MouseListener.
- Q3.Explain byte and character streams with programs.
- Q4.Write a program using RandomAccessFile to read and update records.
Stuck on this unit?
Message SBS on WhatsApp for help with Programming in Java, or to ask about studying B.Sc IT at Synetic.
