The problem isn't with the listeners, it's with your render logic...
if (mouseAction == 'a') {
g.drawString("Mouse entered at (" + x1 + ", " + y1 + ")", 25, 25);
} else if (mouseAction == 'b') {
g.drawString("Mouse exited at (" + x1 + ", " + y1 + ")", 25, 25);
} else if (mouseAction == 'c') {
g.drawString("Mouse moved at (" + x2 + ", " + y2 + ")", 25, 25);
} else if (mouseAction == 'd') {
g.drawString("Mouse clicked at (" + x1 + ", " + y1 + ")", 25, 25);
}
Basically, when the mouse enters, it triggers a mouseAction
of a
, which is immeditly followed by a mouseAction
of c
.
I would surmise that the repaint manager never gets time to render a
because c
overrides it.
If you updated your paint code to separate the logic between motion and action you should be able to see the difference.
g.drawString("Mouse " + (mouseEntered ? "entered" : "exited") + " at (" + x1 + ", " + y1 + ")", 25, 50);
if (mouseAction == 'c') {
g.drawString("Mouse moved at (" + x2 + ", " + y2 + ")", 25, 25);
} else if (mouseAction == 'd') {
g.drawString("Mouse clicked at (" + x1 + ", " + y1 + ")", 25, 25);
}
I added a mouseEntered
field, which is a simple boolean
value, set to true
from mouseEntered
and false
from mouseExited
Also, convention prefers overriding the paintComponent
method rather the paint
. paintComponent
is double buffered, paint
isn't.