MouseEvent and MouseListener
MouseListener is an interface that requires five instance methods: mousePressed, mouseReleased, mouseClicked, mouseEntered, and mouseExited. Empty bodies are allowed, but the methods must all be present.
A Panel That Cannot See the Mouse
Imagine a panel on the screen that shows a few random strings. Suppose you want the panel to show a different string each time the user clicks on it. There is a problem to solve first: the panel itself does not know when a mouse button goes down. Something has to watch for mouse activity and then tell the panel what to do.
In Java GUI programming, that watching object is called a mouse listener. It is written as an object that implements the MouseListener interface. In this article we follow one question from start to finish: when the mouse does something to a component, which code runs, in what order, and how can you make the component redraw itself as a result?
Tracing the Order of One Click
What do you think happens?
When the user clicks once on a component with no mouse movement, which of mousePressed, mouseReleased, and mouseClicked runs first, and what is the order of all three?
Reveal answer
mousePressed, then mouseReleased, then mouseClicked
A plain click calls mousePressed, then mouseReleased, then mouseClicked, in that order, provided the mouse does not move during the press and release.
Read the diagram from top to bottom. Each call is a moment in the click, and the arrows show which call follows which. The first call, mousePressed, happens the moment the button goes down, so the listener can respond immediately. The second call, mouseReleased, happens when the button comes back up. The third call, mouseClicked, comes last.
Notice that mouseClicked is not a separate physical event happening alongside the press. It is a higher-level report that only makes sense after the button has gone down and come back up on the same spot. A press is detected the moment it happens, while a click is known only after the release. This is why the source recommends that most listeners respond to mousePressed rather than mouseClicked.
Why the Listener Must Supply Five Methods
MouseListener is an interface that requires five instance methods: mousePressed, mouseReleased, mouseClicked, mouseEntered, and mouseExited. Each takes a MouseEvent parameter. Empty bodies are allowed, but the methods must all be present.
Think of MouseListener as a contract. Any class that claims to be a mouse listener promises to supply all five methods. The mouse system calls these methods at the right moments, so the listener's job is simply to have them ready. The contract is strict but simple. Two of the methods, mousePressed and mouseReleased, are the ones most often used in practice. The other three exist so that the interface is complete. A listener that needs only one of them still has to supply all five, with a body for each one it does not use.
The diagram shows why the rule exists. The interface names the five methods, and the listener class must provide each one. A method with an empty body is still a method, so it satisfies the contract. The listener can leave mouseClicked empty and still be a valid mouse listener.
Entering and Leaving the Panel
The mouseEntered and mouseExited methods are called when the mouse cursor enters or leaves the component. They do not depend on any button being pressed. Their purpose is to let the listener notice that the pointer has crossed the edge of the component.
One common use is to change how a component looks whenever the pointer moves into or out of it. The response to that change belongs in mouseEntered and mouseExited. Because these two events are triggered by the pointer crossing the boundary rather than by a press, a listener can react to hovering without any click at all.
| Method | What triggers it | Needs a button press? |
|---|---|---|
| mousePressed | Button goes down over the component | Yes, it is the press |
| mouseReleased | Button comes back up | Yes, a press must have happened |
| mouseClicked | Press and release on the same spot with no movement | Yes, it reports a completed click |
| mouseEntered | Cursor crosses into the component | No |
| mouseExited | Cursor crosses out of the component | No |
The five MouseListener methods and what triggers each one
Writing a Listener That Repaints the Panel
The source recommends attaching a listener to the panel and calling repaint() on the panel inside mousePressed. The example below applies that idea to the random string panel from the introduction. The panel implements MouseListener itself, so it can respond to its own presses. It must still supply all five methods, even though only mousePressed does useful work.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class StringPanel extends JPanel implements MouseListener {
private String[] words = {"apple", "river", "lantern", "orbit"};
private Random random = new Random();
private String current = "apple";
public StringPanel() {
addMouseListener(this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(current, 20, 40);
}
public void mousePressed(MouseEvent e) {
current = words[random.nextInt(words.length)];
repaint();
}
public void mouseReleased(MouseEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
}- 1The class extends
JPanelso it is a drawable component, and implementsMouseListenerso the mouse system can call its methods. - 2The constructor attaches the panel as its own mouse listener. Without this line, no press would reach the panel's methods.
- 3
paintComponentis where the panel draws its contents. It stores nothing about the screen; it just draws current. - 4When the button goes down,
mousePressedruns first. It picks a new string and callsrepaint()on the panel. - 5
repaint()does not draw immediately. It asks the panel to redraw, and the redraw callspaintComponent, which now draws the new string. - 6
mouseReleased,mouseClicked,mouseEntered, andmouseExitedare present with empty bodies, as the contract requires.
- implements
MouseListenermakes this panel a listener, so all five methods must appear addMouseListener(this)attaches the listener to the panelmousePressedchooses a new string and asks the panel to repaintpaintComponentdraws whatever string is currently stored- the three empty methods satisfy the contract without doing anything
The panel first shows apple. Each mouse press changes current to one of river, lantern, or orbit and the panel shows that word.Trace the chain in order. The press reaches mousePressed, which updates the stored string and calls repaint(). The panel then schedules a redraw, and the redraw calls paintComponent, which draws the new value. The panel does not repaint on its own: the listener notices the press, and only then asks for the redraw. When debugging, check each link in order, starting with whether the listener is actually attached to the panel.
Initial display: apple
After one press: one of river, lantern, orbit (chosen at random)
After another press: a new random choice from the same listMistakes Beginners Make with Listeners
The following mistakes come up often when learners first implement a listener. Each one is tied to a specific rule from the material above.
Common mistake Leaving out one of the five methods because it is not needed
What it looks likeA class implements MouseListener but has only mousePressed and mouseReleased defined.
Why it failsThe interface requires all five instance methods. Empty bodies are allowed, but the methods must be present.
Do this insteadKeep all five methods and leave the unused ones with empty bodies.
Common mistake Responding to mouseClicked when the press is what matters
What it looks likeThe panel changes its text only in mouseClicked, so a press that moves slightly never updates it.
Why it failsA click is only reported after the button comes back up on the same spot. If the mouse moves,
mouseClickedis not reported.Do this insteadRespond to mousePressed in most cases, since a press is detected the moment it happens.
Common mistake Calling repaint() but expecting the panel to change at once from other code
What it looks likeThe listener changes the stored string, but the panel never shows the new text.
Why it failsThe panel redraws only when
repaint()is called, and that redraw is what callspaintComponent.Do this insteadCall repaint() on the panel after changing the data it draws.
Common mistake Forgetting to attach the listener to the panel
What it looks likeThe class implements MouseListener correctly, but addMouseListener is never called.
Why it failsThe panel itself does not know when a mouse button goes down. Without attachment, nothing tells the listener about mouse activity.
Do this insteadAttach the listener to the panel, as the constructor does with addMouseListener(this).
Tracing a Click That Does Not Register
A learner's StringPanel is attached as a mouse listener and calls repaint() in mousePressed. When the user clicks, the panel does not change. Using the order of one click, list the calls that should run during a clean click, then explain where the chain breaks if the user's hand moves slightly while the button is held down.
Hints
- Start with the order
mousePressed, thenmouseReleased, thenmouseClicked. - Ask whether
mousePressedstill runs when the mouse moves, and what happens tomouseClicked. - Remember that
repaint()is called insidemousePressed, so the redraw depends on that method running.
Add a mouseEntered method to StringPanel so the panel shows a different background color while the cursor is over it. Keep the other four methods in the class. Explain which method you changed and why the other four must still be present.
Hints
mouseEntereddoes not depend on a button press.- A background change needs a repaint, just like the string change does.
Key Takeaways
MouseListeneris an interface requiring five instance methods:mousePressed,mouseReleased,mouseClicked,mouseEntered, andmouseExited, each taking aMouseEventparameter.- All five methods must be present, though their bodies may be empty, because the interface is a contract the mouse system relies on.
- A plain click calls
mousePressed, thenmouseReleased, thenmouseClicked, provided the mouse does not move; that is why most listeners respond tomousePressed. mouseEnteredandmouseExitedrespond to the pointer crossing the component's edge and do not require a button press.- To repaint a panel on click, attach the listener, call
repaint()insidemousePressed, and remember that the redraw then callspaintComponent.