Afraid there are various things about that code I don't like, apart from the
lines too long.
Move the
{...} so the DrawPanel class is entirely inside the GUI class, and give it
private access. That is a minor point, but it means you can have a class with the same name elsewhere without causing yourself any confusion.
More serious: I don't like to see display classes implement
XYZListener interfaces. Sometimes such interfaces are unavoidable and can be implemented correctly like that, but I think not an action listener. Delete the
implements clause, and write the implementation inside the method call in line 21. Fortunately,
action listener is a
functional interface, even though the documentation doesn't mention it, so you can reduce that listener to a λ:-
Less serious: Preface the
paintComponent() with the
@Override annotation, and change its access to
protected. You should never call that method, but leave the JVM to call it. Insert the following as the first line of
paintComponent() whenever you override it:-
super.paintComponent(g); This will cause the panel to revert to its original appearance (like its superclass) so you don't end up with multiple pictures painted on top of one another.
The idea is, when you click the button, an event object (actually an
ActionEvent) is sent from the button to its enclosing components, to see whether there is anything that can listen for it. If nothing is listening, the event keeps going until it reaches the (I think, not certain) ?glass pane? of its top‑level component, and if it still hasn't been listened for, it vanishes into some sort of cyber‑limbo never to be seen again.
But you have written something to listen for that event. I think you should change where it is listened for to the
button, and remove the
actionPerformed() method, but that won't make much difference in this simple case. The way I wrote it, the button will listen for, and intercept the event, and then fire the
actionPerformed() and that calls
repaint(). Now,
repaint() calls all sorts of methods including
paintComponent() on every component in sight, and in the case of the
DrawPanel, it causes the coloured oval to be painted anew in a different colour. . . . or it would have if you had remembered to add the button and panel to the frame!