Event Listeners

Event Listeners are interfaces in Java Swing that define methods for responding to user actions or events. Components generate events, and listeners handle them.


Commonly Used Listener Interfaces

Listener InterfaceDescriptionMethod Signature
ActionListenerFor button clicks and similar actionsvoid actionPerformed(ActionEvent e)
MouseListenerMouse click, enter, exit, etc.void mouseClicked(MouseEvent e) (and others)
KeyListenerKeyboard key press and releasevoid keyPressed(KeyEvent e) (and others)
WindowListenerWindow open, close, minimize, etc.void windowClosing(WindowEvent e) (and others)

Example: ActionListener

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Action performed!");
    }
});

Example: MouseListener

label.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        System.out.println("Mouse clicked!");
    }
});

MouseAdapter is an abstract adapter class that lets you override only the needed methods.