Unit 4 of 4 · B.Sc IT Sem 5

Unit 4: AWT, event handling and I/O

Programming in Java notes · PTU syllabus (BSIT502/BSBC502)

3 min read8 topics10 exam questions
On this page
  1. Unit summary
  2. AWT containers
  3. UI components and layouts
  4. The event delegation model
  5. Event handling program
  6. I/O streams
  7. FileInputStream and FileOutputStream
  8. Reader and writer streams
  9. Random access files
  10. Key terms
  11. Quick revision
  12. Important questions

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
ProcessEvent delegation model
  1. 1User acts

    Clicks a button

  2. 2Source creates an event object

    ActionEvent

  3. 3Event sent to registered listener
  4. 4Listener method runs

    actionPerformed()

1

Topic 1

AWT containers

ClassificationAWT hierarchy
Component
  • 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.
2

Topic 2

UI components and layouts

ComparisonLayout managers
Arrangement
Default for

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

—

3

Topic 3

The event delegation model

ProcessEvent delegation model
  1. 1Source

    Component generates an event — button click

  2. 2Event object

    ActionEvent carries details

  3. 3Registration

    Listener registered with addActionListener

  4. 4Listener

    Receives the event and runs the handler method

Key termsListeners and methods
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
4

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(); }
}
5

Topic 5

I/O streams

ComparisonByte and character streams
Byte streams
Character 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).
6

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()); }
7

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]);
    }
}
8

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

  1. Q1.Distinguish Frame and Panel.
  2. Q2.Which is the default layout of a Frame?
  3. Q3.What is the event delegation model?
  4. Q4.What is an adapter class?
  5. Q5.Distinguish byte and character streams.
  6. Q6.What does seek() do?

Long-answer questions

  1. Q1.Explain AWT containers, components and layout managers.
  2. Q2.Explain event handling with a program using ActionListener and MouseListener.
  3. Q3.Explain byte and character streams with programs.
  4. 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.

WhatsApp us