Introduction to AWT and Applets · Introduction to Java Programming

Listener Methods

Watch lectures

Listener Methods

1. What Are Listener Methods? (beginner)

Callbacks JVM calls on events (you write body, JVM invokes!). Each listener = fixed method names (spell EXACT, use @Override!).

2. Master Table (exam — memorize pairs!)

Listener Methods (all!)
ActionListener actionPerformed(e) (1!)
WindowListener windowOpened/Closing/Closed/Iconified/Deiconified/Activated/Deactivated (7!)
MouseListener mouseClicked/Pressed/Released/Entered/Exited (5!)
MouseMotionListener mouseDragged/Moved (2!)
KeyListener keyPressed/Released/Typed (3!)
TextListener textValueChanged(e) (1!)

3. Code — Mouse + Key Snoop (print events!)

addMouseListener(new MouseAdapter() { // adapter (1 method!)
    @Override public void mouseClicked(MouseEvent e) {
        System.out.println("click at " + e.getX() + "," + e.getY());
    }
});
addKeyListener(new KeyAdapter() {
    @Override public void keyPressed(KeyEvent e) {
        System.out.println("key: " + e.getKeyChar() + " code=" + e.getKeyCode());
    }
});
// focus needed for keys: setFocusable(true); requestFocus();

Event getters: getSource() (who?), getX/getY (mouse!), getKeyChar (key!).

4. Traps

  • mouseClicked needs press+release same spot (else use Pressed!).
  • Keys need FOCUS (click window first!). Buttons eat keys (add to Frame!).
  • Adapters exist for Window/Mouse/Key (NOT Action — 1 method already!).

5. Exam Points

  • Table + snoop program — 7 marks, very frequent.
  • Adapter availability + focus — 3 marks, frequent.
AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.

← All Introduction to Java Programming modules