Mouse Events and the AWT Event Hierarchy in Java
Handling the mouse in Swing: pressed, released and clicked events, click counts, drags, the wheel, buttons and modifiers, popup triggers and cursors, built into a small square editor; then the AWT event hierarchy, semantic versus low-level events, and the listener interfaces.
kvi5hnuCode Sprout team member11 min readOn this page
Buttons and menus handle the mouse for you: you only hear about the resulting action event. Some components, though, need the raw mouse: a drawing program, a chart you can zoom, a board game, a diagram editor. This article shows how to receive and interpret mouse events, using a small editor in which you add, move and delete squares. It then steps back to survey the whole family of AWT event classes and listener interfaces.
Clicks: MouseListener
MouseListener has five methods:
| Method | Called when |
|---|---|
mousePressed | A mouse button goes down over the component. |
mouseReleased | The button comes up (delivered to the component where the press started). |
mouseClicked | Press and release happened at the same spot, after mouseReleased. |
mouseEntered, mouseExited | The pointer moves into or out of the component. |
A single click therefore produces three calls: pressed, released, clicked. Use mousePressed for immediate feedback (the editor adds a square the moment the button goes down) and mouseClicked when you need to know it was a complete click.
MouseEvent tells you where and how:
getX(),getY()andgetPoint()give the position relative to the top-left corner of the source component.getXOnScreen()/getYOnScreen()give screen coordinates, andSwingUtilities.convertPointconverts between components.getClickCount()counts rapid consecutive clicks: 2 for a double-click, 3 for a triple-click. The time window is set by the operating system. A double-click delivers a click with count 1 first and then one with count 2, so a handler for both must cope with that sequence.getButton()reports which button changed (BUTTON1,BUTTON2,BUTTON3).SwingUtilities.isLeftMouseButton(e),isMiddleMouseButtonandisRightMouseButtonare clearer.isShiftDown(),isControlDown(),isAltDown(),isMetaDown()andgetModifiersEx()report modifier keys and held buttons as bit masks such asInputEvent.SHIFT_DOWN_MASKandBUTTON1_DOWN_MASK. Use the...DOWN_MASKconstants withgetModifiersEx; the oldergetModifiersand its masks are deprecated.
Context menus
The gesture for a context menu differs between platforms: right-button press on macOS and Linux, right-button release on Windows, Ctrl+click on macOS. e.isPopupTrigger() knows the local convention, but you must check it in both mousePressed and mouseReleased. Simpler still, give the component a popup menu with setComponentPopupMenu(menu) and let Swing handle the gesture (article 96).
Movement: MouseMotionListener
Mouse movement produces a stream of events, potentially hundreds per second. To spare components that care only about clicks, motion events go to a separate interface, MouseMotionListener:
mouseMovedwhile no button is held and the pointer is over the component;mouseDraggedwhile a button is held. Drag events keep coming even after the pointer leaves the component, until the button is released, so a dragged object can follow the mouse anywhere.
The editor changes the cursor in mouseMoved when the pointer is over a square, and moves the selected square in mouseDragged, then calls repaint().
Cursors
component.setCursor(Cursor.getPredefinedCursor(type)) changes the pointer shape while it is over the component. Predefined types include DEFAULT_CURSOR, CROSSHAIR_CURSOR, HAND_CURSOR, MOVE_CURSOR, TEXT_CURSOR, WAIT_CURSOR, and eight resize cursors named after compass directions (N_RESIZE_CURSOR, NE_RESIZE_CURSOR, ..., NW_RESIZE_CURSOR). Their look depends on the platform. Toolkit.getDefaultToolkit().createCustomCursor(image, hotSpot, name) makes your own.
The wheel: MouseWheelListener
MouseWheelListener.mouseWheelMoved(MouseWheelEvent) reports wheel and trackpad scrolling. getWheelRotation() gives whole notches (negative means away from the user, "up"); getPreciseWheelRotation() gives fractional amounts from high-resolution wheels and trackpads; getScrollType() and getScrollAmount() describe what the platform would scroll. Scroll panes handle the wheel themselves; add your own listener for zooming or adjusting values. In the editor, the wheel changes the size of all squares.
One adapter for all three
MouseAdapter implements MouseListener, MouseMotionListener and MouseWheelListener with empty methods. Override the ones you need in one object and register it three times:
var handler = new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) { ... }
@Override public void mouseDragged(MouseEvent e) { ... }
};
component.addMouseListener(handler);
component.addMouseMotionListener(handler);
(There is also a MouseMotionAdapter for motion only.) Registering a listener is what makes a lightweight component receive those events at all; adding a mouse listener to a component also makes it "opaque" to the mouse, so its parent no longer sees clicks on it.
The complete editor as a windowed program:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class SquaresEditor {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
var frame = new JFrame("Squares: click to add, drag to move, double-click to delete");
frame.add(new SquaresComponent());
frame.pack();
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class SquaresComponent extends JComponent {
private static final long serialVersionUID = 1L;
private static final double SIDE = 20;
private final transient List<Rectangle2D> squares = new ArrayList<>();
private transient Rectangle2D current;
SquaresComponent() {
var handler = new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
current = find(e.getPoint());
if (current == null && SwingUtilities.isLeftMouseButton(e)) add(e.getPoint());
}
@Override public void mouseClicked(MouseEvent e) {
current = find(e.getPoint());
if (current != null && e.getClickCount() >= 2) remove(current);
}
@Override public void mouseMoved(MouseEvent e) {
setCursor(Cursor.getPredefinedCursor(
find(e.getPoint()) == null ? Cursor.DEFAULT_CURSOR : Cursor.MOVE_CURSOR));
}
@Override public void mouseDragged(MouseEvent e) {
if (current != null) {
current.setFrame(e.getX() - SIDE / 2, e.getY() - SIDE / 2, SIDE, SIDE);
repaint();
}
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
}
private Rectangle2D find(Point2D p) {
for (Rectangle2D r : squares) if (r.contains(p)) return r;
return null;
}
private void add(Point2D p) {
current = new Rectangle2D.Double(p.getX() - SIDE / 2, p.getY() - SIDE / 2, SIDE, SIDE);
squares.add(current);
repaint();
}
private void remove(Rectangle2D r) {
squares.remove(r);
if (r == current) current = null;
repaint();
}
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g;
for (Rectangle2D r : squares) g2.draw(r);
}
@Override public Dimension getPreferredSize() { return new Dimension(400, 300); }
}
The transient modifiers silence serialization warnings: Swing components are Serializable, but Rectangle2D is not, and nobody serializes this component anyway.
The AWT event hierarchy
All AWT events descend from java.awt.AWTEvent, which extends java.util.EventObject:

Swing components add their own events, such as ChangeEvent (a slider moved), ListSelectionEvent and TreeSelectionEvent. These extend EventObject directly, not AWTEvent, and live in javax.swing.event. (DocumentEvent, used by text components, is an interface.)
Some AWT event classes never reach your code. The AWT puts PaintEvents in the queue, but they are not delivered to listeners; you control painting by overriding paintComponent. Other events exist for input methods (entering Chinese or Japanese text) and for testing robots.
Semantic and low-level events
The AWT distinguishes two kinds of events:
- Semantic events express what the user wants: "this button was activated", "this item was chosen".
ActionEvent(button click, menu selection, Enter in a text field, a double-click in an AWTList(a SwingJListhas no action events), aTimertick),AdjustmentEvent(a scroll bar moved) andItemEvent(a check box or list item was selected) are the common ones. - Low-level events are the raw input from which semantic events are made:
KeyEvent,MouseEvent,MouseWheelEvent,FocusEvent,WindowEvent,ComponentEvent(moved, resized, shown, hidden) andContainerEvent(child added or removed).
A button click is one semantic event built from several low-level ones: mouse pressed over the button, perhaps some moves, mouse released over the button. If the user presses inside the button, moves outside and releases there, no action event occurs, which is how users "cancel" a click. The same action event can come from the keyboard: Tab to the button, press Space. Listening for the semantic event covers all those ways; the demo shows both cases.
Prefer semantic events whenever one exists. In particular, use key bindings (article 90) rather than a KeyListener for shortcuts: a KeyListener only hears keys while its own component has focus.
Listener summary
| Listener interface | Methods | Event and useful accessors | Typical sources |
|---|---|---|---|
ActionListener | actionPerformed | ActionEvent: getActionCommand, getModifiers | AbstractButton, JComboBox, JTextField, Timer |
AdjustmentListener | adjustmentValueChanged | AdjustmentEvent: getAdjustable, getAdjustmentType, getValue | JScrollBar |
ItemListener | itemStateChanged | ItemEvent: getItem, getItemSelectable, getStateChange | AbstractButton, JComboBox |
FocusListener | focusGained, focusLost | FocusEvent: isTemporary, getOppositeComponent | Component |
KeyListener | keyPressed, keyReleased, keyTyped | KeyEvent: getKeyChar, getKeyCode, getKeyText, isActionKey | Component |
MouseListener | mousePressed, mouseReleased, mouseClicked, mouseEntered, mouseExited | MouseEvent: getX, getY, getPoint, getClickCount, getButton | Component |
MouseMotionListener | mouseDragged, mouseMoved | MouseEvent | Component |
MouseWheelListener | mouseWheelMoved | MouseWheelEvent: getWheelRotation, getPreciseWheelRotation | Component |
WindowListener | windowOpened, windowClosing, windowClosed, windowIconified, windowDeiconified, windowActivated, windowDeactivated | WindowEvent: getWindow | Window |
WindowFocusListener | windowGainedFocus, windowLostFocus | WindowEvent: getOppositeWindow | Window |
WindowStateListener | windowStateChanged | WindowEvent: getOldState, getNewState | Window |
ComponentListener | componentMoved, componentResized, componentShown, componentHidden | ComponentEvent: getComponent | Component |
A key event detail: keyPressed and keyReleased report virtual key codes (KeyEvent.VK_A, VK_SHIFT, VK_F5), one per physical key, while keyTyped reports the character that resulted ('A' when Shift+A is pressed). Use keyTyped for text and the virtual codes for keys such as arrows and function keys.
The program
The demo runs the editor's component without a window. It builds MouseEvents by hand (the same objects the AWT creates from real input) and dispatches them on the EDT with dispatchEvent, then paints the component into an image and prints it. It adds two squares (ignoring a right click), drags one, turns the wheel, and double-clicks to delete; prints the details of a shift-click; sends press/release pairs to a JButton to show how low-level events turn into an ActionEvent; and prints the superclass chains of several event classes.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
public class Solution {
/** Click to add a square, drag to move it, double-click to delete, wheel to resize. */
static class SquaresComponent extends JComponent {
private static final long serialVersionUID = 1L;
private final transient List<Rectangle2D> squares = new ArrayList<>();
private transient Rectangle2D current; // the square under the mouse, if any
private int side = 6;
SquaresComponent() {
var handler = new MouseAdapter() { // one adapter serves three listener interfaces
@Override public void mousePressed(MouseEvent e) {
current = find(e.getPoint());
if (current == null && SwingUtilities.isLeftMouseButton(e)) add(e.getPoint());
}
@Override public void mouseClicked(MouseEvent e) {
current = find(e.getPoint());
if (current != null && e.getClickCount() >= 2) remove(current);
}
@Override public void mouseMoved(MouseEvent e) {
setCursor(Cursor.getPredefinedCursor(find(e.getPoint()) == null
? Cursor.DEFAULT_CURSOR : Cursor.MOVE_CURSOR));
}
@Override public void mouseDragged(MouseEvent e) {
if (current != null) {
current.setFrame(e.getX() - side / 2.0, e.getY() - side / 2.0, side, side);
repaint();
}
}
@Override public void mouseWheelMoved(MouseWheelEvent e) {
side = Math.max(2, side - e.getWheelRotation() * 2); // wheel up (negative) = bigger
for (Rectangle2D r : squares)
r.setFrameFromCenter(r.getCenterX(), r.getCenterY(), r.getCenterX() + side / 2.0, r.getCenterY() + side / 2.0);
repaint();
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
addMouseWheelListener(handler);
}
Rectangle2D find(Point2D p) {
for (Rectangle2D r : squares) if (r.contains(p)) return r;
return null;
}
void add(Point2D p) {
current = new Rectangle2D.Double(p.getX() - side / 2.0, p.getY() - side / 2.0, side, side);
squares.add(current);
repaint();
}
void remove(Rectangle2D r) {
squares.remove(r);
if (r == current) current = null;
repaint();
}
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g;
g2.setPaint(Color.BLACK);
for (Rectangle2D r : squares) g2.draw(r);
}
@Override public Dimension getPreferredSize() { return new Dimension(40, 14); }
}
static int clock;
static void send(Component c, int id, int x, int y, int button, int modifiersEx, int clicks) {
var e = new MouseEvent(c, id, clock++, modifiersEx, x, y, clicks, false, button);
c.dispatchEvent(e);
}
static void show(SquaresComponent comp, String title) {
var img = new BufferedImage(40, 14, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setPaint(Color.WHITE);
g.fillRect(0, 0, 40, 14);
comp.paint(g);
g.dispose();
System.out.println(title + " (" + comp.squares.size() + " squares, cursor: " + cursorName(comp) + ")");
for (int y = 0; y < 14; y++) {
var sb = new StringBuilder(" ");
for (int x = 0; x < 40; x++) sb.append((img.getRGB(x, y) & 0xFFFFFF) == 0 ? '#' : '.');
System.out.println(sb);
}
}
static String cursorName(Component c) {
return switch (c.getCursor().getType()) {
case Cursor.DEFAULT_CURSOR -> "DEFAULT";
case Cursor.MOVE_CURSOR -> "MOVE";
default -> "other";
};
}
static String chain(Class<?> c) {
var names = new ArrayList<String>();
for (; c != Object.class; c = c.getSuperclass()) names.add(c.getSimpleName());
return String.join(" -> ", names);
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
EventQueue.invokeAndWait(Solution::run);
}
static void run() {
var comp = new SquaresComponent();
comp.setSize(comp.getPreferredSize());
int b1 = InputEvent.BUTTON1_DOWN_MASK;
System.out.println("== Mouse events drive a small editor ==");
send(comp, MouseEvent.MOUSE_PRESSED, 6, 6, MouseEvent.BUTTON1, b1, 1);
send(comp, MouseEvent.MOUSE_RELEASED, 6, 6, MouseEvent.BUTTON1, 0, 1);
send(comp, MouseEvent.MOUSE_CLICKED, 6, 6, MouseEvent.BUTTON1, 0, 1);
send(comp, MouseEvent.MOUSE_PRESSED, 20, 7, MouseEvent.BUTTON1, b1, 1);
send(comp, MouseEvent.MOUSE_RELEASED, 20, 7, MouseEvent.BUTTON1, 0, 1);
send(comp, MouseEvent.MOUSE_PRESSED, 30, 4, MouseEvent.BUTTON3, InputEvent.BUTTON3_DOWN_MASK, 1); // right button: ignored
show(comp, "after clicks at (6,6), (20,7) and a right click");
send(comp, MouseEvent.MOUSE_MOVED, 20, 7, MouseEvent.NOBUTTON, 0, 0);
System.out.println("mouse over a square -> cursor: " + cursorName(comp));
send(comp, MouseEvent.MOUSE_PRESSED, 20, 7, MouseEvent.BUTTON1, b1, 1);
for (int x = 22; x <= 32; x += 2) // drag in steps
send(comp, MouseEvent.MOUSE_DRAGGED, x, 7, MouseEvent.NOBUTTON, b1, 0);
send(comp, MouseEvent.MOUSE_RELEASED, 32, 7, MouseEvent.BUTTON1, 0, 1);
show(comp, "after dragging the second square to x=32");
comp.dispatchEvent(new MouseWheelEvent(comp, MouseEvent.MOUSE_WHEEL, clock++, 0, 6, 6, 0, false,
MouseWheelEvent.WHEEL_UNIT_SCROLL, 3, -1));
show(comp, "after one wheel notch up");
send(comp, MouseEvent.MOUSE_CLICKED, 6, 6, MouseEvent.BUTTON1, 0, 1);
send(comp, MouseEvent.MOUSE_CLICKED, 6, 6, MouseEvent.BUTTON1, 0, 2);
send(comp, MouseEvent.MOUSE_MOVED, 6, 6, MouseEvent.NOBUTTON, 0, 0);
show(comp, "after double-clicking the first square");
System.out.println("\n== What a MouseEvent carries ==");
var listener = new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
System.out.println("pressed at (" + e.getX() + ", " + e.getY() + "), button " + e.getButton()
+ ", click count " + e.getClickCount() + ", shift down: " + e.isShiftDown()
+ ", ctrl down: " + e.isControlDown());
System.out.println("left button: " + SwingUtilities.isLeftMouseButton(e)
+ ", BUTTON1_DOWN_MASK set: " + ((e.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) != 0)
+ ", popup trigger: " + e.isPopupTrigger());
}
};
comp.addMouseListener(listener);
send(comp, MouseEvent.MOUSE_PRESSED, 3, 9, MouseEvent.BUTTON1, b1 | InputEvent.SHIFT_DOWN_MASK, 1);
comp.removeMouseListener(listener);
System.out.println("\n== Low-level events become a semantic event ==");
var button = new JButton("OK");
button.setSize(40, 20);
button.addActionListener(e -> System.out.println("ActionEvent: \"" + e.getActionCommand() + "\""));
button.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) { System.out.println("MouseEvent: pressed"); }
@Override public void mouseReleased(MouseEvent e) { System.out.println("MouseEvent: released"); }
});
send(button, MouseEvent.MOUSE_PRESSED, 10, 10, MouseEvent.BUTTON1, b1, 1);
send(button, MouseEvent.MOUSE_RELEASED, 10, 10, MouseEvent.BUTTON1, 0, 1);
System.out.println("press inside, release outside:");
send(button, MouseEvent.MOUSE_PRESSED, 10, 10, MouseEvent.BUTTON1, b1, 1);
send(button, MouseEvent.MOUSE_EXITED, 60, 10, MouseEvent.NOBUTTON, b1, 0);
send(button, MouseEvent.MOUSE_RELEASED, 60, 10, MouseEvent.BUTTON1, 0, 1);
System.out.println("\n== The event class hierarchy ==");
for (Class<?> c : List.of(MouseWheelEvent.class, KeyEvent.class, ActionEvent.class, ItemEvent.class,
WindowEvent.class, ChangeEvent.class))
System.out.println(chain(c));
}
}
== Mouse events drive a small editor ==
after clicks at (6,6), (20,7) and a right click (2 squares, cursor: DEFAULT)
........................................
........................................
........................................
...#######..............................
...#.....#.......#######................
...#.....#.......#.....#................
...#.....#.......#.....#................
...#.....#.......#.....#................
...#.....#.......#.....#................
...#######.......#.....#................
.................#######................
........................................
........................................
........................................
mouse over a square -> cursor: MOVE
after dragging the second square to x=32 (2 squares, cursor: MOVE)
........................................
........................................
........................................
...#######..............................
...#.....#...................#######....
...#.....#...................#.....#....
...#.....#...................#.....#....
...#.....#...................#.....#....
...#.....#...................#.....#....
...#######...................#.....#....
.............................#######....
........................................
........................................
........................................
after one wheel notch up (2 squares, cursor: MOVE)
........................................
........................................
..#########.............................
..#.......#.................#########...
..#.......#.................#.......#...
..#.......#.................#.......#...
..#.......#.................#.......#...
..#.......#.................#.......#...
..#.......#.................#.......#...
..#.......#.................#.......#...
..#########.................#.......#...
............................#########...
........................................
........................................
after double-clicking the first square (1 squares, cursor: DEFAULT)
........................................
........................................
........................................
............................#########...
............................#.......#...
............................#.......#...
............................#.......#...
............................#.......#...
............................#.......#...
............................#.......#...
............................#.......#...
............................#########...
........................................
........................................
== What a MouseEvent carries ==
pressed at (3, 9), button 1, click count 1, shift down: true, ctrl down: false
left button: true, BUTTON1_DOWN_MASK set: true, popup trigger: false
== Low-level events become a semantic event ==
MouseEvent: pressed
ActionEvent: "OK"
MouseEvent: released
press inside, release outside:
MouseEvent: pressed
MouseEvent: released
== The event class hierarchy ==
MouseWheelEvent -> MouseEvent -> InputEvent -> ComponentEvent -> AWTEvent -> EventObject
KeyEvent -> InputEvent -> ComponentEvent -> AWTEvent -> EventObject
ActionEvent -> AWTEvent -> EventObject
ItemEvent -> AWTEvent -> EventObject
WindowEvent -> ComponentEvent -> AWTEvent -> EventObject
ChangeEvent -> EventObject
Points to notice:
- The drag ended with the square centered on the last drag position; the editor did not need the release event at all.
- The double-click arrived as a click with count 1 followed by one with count 2, and only the second deleted the square.
- The button's own mouse listener saw both press/release pairs, but only the first, released inside the button, produced an
ActionEvent. ChangeEvent, a Swing event, extendsEventObjectdirectly and is not anAWTEvent.
Common questions
How do I detect a double click?
In mouseClicked, check e.getClickCount() == 2. The platform decides the time window. Note that the first click of a double click also arrives as a single click, so design single-click actions to be harmless (select) and double-click actions to build on them (open).
How do I tell left, right and middle buttons apart?
SwingUtilities.isLeftMouseButton(e), isRightMouseButton(e) and isMiddleMouseButton(e), or e.getButton() compared with MouseEvent.BUTTON1 to BUTTON3. For context menus, use isPopupTrigger() or setComponentPopupMenu.
Why do I get no mouseDragged events?
Drags are motion events. Register the listener with addMouseMotionListener too; registering a MouseAdapter only with addMouseListener delivers just clicks.
How do I get mouse coordinates relative to another component?
SwingUtilities.convertPoint(source, e.getPoint(), target), or e.getLocationOnScreen() for screen coordinates.
How do I implement drag-and-drop between components?
For data transfer, use Swing's TransferHandler and setDragEnabled(true) on components that support it. For moving shapes inside your own component, the press/drag/release pattern in this article is the right tool.
API reference
| Class / method | Purpose |
|---|---|
addMouseListener, addMouseMotionListener, addMouseWheelListener | Register mouse listeners. |
MouseAdapter | Empty implementations of all three mouse listener interfaces. |
MouseEvent.getX/getY/getPoint, getXOnScreen/getYOnScreen | Position. |
getClickCount, getButton, isPopupTrigger, getModifiersEx | Click details. |
SwingUtilities.isLeftMouseButton/isMiddleMouseButton/isRightMouseButton, convertPoint | Helpers. |
MouseWheelEvent.getWheelRotation, getPreciseWheelRotation, getScrollType, getScrollAmount | Wheel details. |
Component.setCursor, Cursor.getPredefinedCursor, Toolkit.createCustomCursor | Pointer shape. |
JComponent.setComponentPopupMenu | Context menu with the platform's trigger. |
AWTEvent, EventObject.getSource | Event roots. |
KeyEvent.getKeyCode, getKeyChar, KeyEvent.getKeyText | Key details. |
Summary
MouseListenerreports presses, releases, clicks (with click counts) and entering/leaving;MouseMotionListenerreports moves and drags (drags continue outside the component);MouseWheelListenerreports the wheel.MouseAdaptercovers all three.- Positions are relative to the source component. Identify buttons with
SwingUtilities.is...MouseButtonand modifiers withgetModifiersEx; detect context menus withisPopupTriggerin both press and release, or usesetComponentPopupMenu. - Change the pointer with
setCursorto signal what a click or drag will do. - AWT events extend
AWTEvent; Swing's own events extendEventObject. Semantic events (action, item, adjustment) describe user intent and are built from low-level events (mouse, key, focus, window). Listen to semantic events when you can.
Practice Questions
1. Your component should select a shape on single click and open an editor on double-click. With mouseClicked, the editor opens but the selection code also runs. Why?
A double-click is delivered as two mouseClicked events: the first with getClickCount() == 1, the second with 2. The first one runs your single-click code. Design the single-click action so that it is harmless before a double-click (selecting first, then opening, is natural), or delay the single-click action with a timer and cancel it if a second click arrives.
2. A drag handler stops getting events when the pointer leaves a small component. Is that expected?
No. Once a button is pressed over a component, mouseDragged events keep going to that component until the button is released, even when the pointer is outside it. Only mouseMoved (no button held) stops at the component's boundary. If drags stop, the code probably uses mouseMoved, or the listener was registered with addMouseListener only, which does not deliver motion events; register it with addMouseMotionListener too.
3. A context menu works on macOS but not on Windows. The code checks isPopupTrigger() in mousePressed. What is wrong?
On Windows the popup trigger is the right-button release, so isPopupTrigger() is false in mousePressed and true only in mouseReleased. Check it in both methods, or use setComponentPopupMenu, which lets Swing apply the platform's rule automatically.
4. Explain the difference between a semantic and a low-level event using a JButton.
The low-level events are the raw input: mouse pressed, mouse moved, mouse released, or key pressed/released for Space when the button has focus. The button turns a valid sequence of them (press and release inside it, or Space while focused) into one semantic ActionEvent: "the button was activated". An action listener reacts correctly to every way of activating the button, while a mouse listener would miss the keyboard and wrongly react to press-drag-release sequences that users intend as cancellations.
5. Which event method would you use to implement arrow-key movement in a game, and which to collect typed text?
For arrow keys, react to keyPressed with the virtual key codes KeyEvent.VK_LEFT and so on, ideally through key bindings so the component does not need a KeyListener and focus handling. For typed text, use keyTyped and getKeyChar(), which gives the resulting character after Shift, dead keys and keyboard layouts are applied; better still, use a text component, which handles input methods too.
Previous: Event Handling in Swing: Listeners, Adapters and Actions
Related reading
- Event Handling in Swing: Listeners, Adapters and Actions
- Drawing with Java 2D: Shapes, Colors, Fonts and Images
- Java GUI Toolkits and Your First JFrame: AWT, Swing and JavaFX
- Public Key Encryption in Java: RSA, Hybrid Encryption and ML-KEM
- Symmetric Encryption in Java: AES-GCM, Key Generation and Cipher Streams

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.