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
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.
Example
Building a window: Frame f = new Frame("Login"); f.add(new Button("OK")); f.setSize(300, 200); f.setVisible(true); creates a window containing one button.
Exam tip
Containers (Frame, Panel, Applet) hold components; components (Button, Label, TextField) are the visible controls.
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
—
Example
Choosing a layout: a calculator keypad uses GridLayout(4, 4) for equal-sized buttons; a main window uses BorderLayout with a toolbar at NORTH and a status bar at SOUTH; a simple form uses FlowLayout.
Exam tip
Frame's default is BorderLayout; Panel's and Applet's default is FlowLayout.
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
Example
The three steps of event handling: for a button that shows a greeting — (1) the class implements ActionListener; (2) the button registers it with btn.addActionListener(this); (3) actionPerformed(ActionEvent e) sets label.setText("Hello"). Click the button → the button (source) creates an ActionEvent → the registered listener's method runs.
Exam tip
To handle only one window event (closing the window), extend WindowAdapter and override just windowClosing, instead of implementing all seven methods of WindowListener. Adapter classes exist for listeners with more than one method.
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
A stream is a sequence of data flowing from a source to a destination. Byte streams (InputStream, OutputStream) handle binary data; character streams (Reader, Writer) handle text.
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
Exam tip
Choose the stream by the data: images, audio and other binary files → byte streams (FileInputStream, FileOutputStream); text → character streams (FileReader, FileWriter), wrapped in BufferedReader to read a line at a time with readLine().
- Standard streams: System.in (InputStream), System.out and System.err (PrintStream). The File class gives file information (exists, length, delete, list).
Example
Choosing a stream: to copy an image file, use FileInputStream and FileOutputStream (bytes); to read a text file line by line, use BufferedReader with FileReader (characters).
Exam tip
Byte streams for binary files; character streams for text files.
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()); }Example
Copying a file: int b; while ((b = in.read()) != -1) out.write(b); copies photo.jpg to copy.jpg one byte at a time. read() returns −1 at the end of the file.
Exam tip
Use try-with-resources so streams close automatically.
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]);
}
}Example
Writing and reading text: bw.write("Asha 88"); bw.newLine(); writes lines to marks.txt; String line; while ((line = br.readLine()) != null) System.out.println(line); reads them back.
Exam tip
BufferedReader.readLine() returns null at the end of the file.
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.
