Introduction to AWT and Applets · Introduction to Java Programming

Listeners

1. What Is a Listener? (beginner)

Listener = interface with reply methods (ears waiting!). Button→ActionListener, window→WindowListener, mouse→MouseListener, key→KeyListener. Register ear on source, JVM calls when event fires!

2. Main Listeners (exam table!)

Source Listener Key method
Button/Menu ActionListener actionPerformed(e)
Window (X) WindowListener windowClosing(e)
Mouse click/move MouseListener / MouseMotionListener mouseClicked(e)
Keyboard KeyListener keyPressed(e)
Text change TextListener textValueChanged(e)

3. Code — Two Ears (button + window!)

class Win extends Frame implements ActionListener, WindowListener {
    Button b = new Button("hi");
    Win() {
        b.addActionListener(this); // ear 1!
        addWindowListener(this);   // ear 2!
        add(b); setSize(250,150); setLayout(new FlowLayout()); setVisible(true);
    }
    public void actionPerformed(ActionEvent e) { System.out.println("clicked!"); }
    public void windowClosing(WindowEvent e) { dispose(); } // + 6 stubs!
    public void windowOpened(WindowEvent e) {} // ... (stub rest!)
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
}

Adapters (WindowAdapter, MouseAdapter) = shortcut (override 1, skip stubs!).

4. Traps

  • implements ALL methods (else abstract!). Adapters avoid stubs!
  • One class MANY listeners (comma-separated implements!).

5. Exam Points

  • Table + two-listener program — 7 marks, very frequent.
  • Adapter vs Listener — 3 marks, frequent.
Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.

← All Introduction to Java Programming modules