HI, all. I've started to learn Java and struggled with a task TwoButtons (chapter 12). When I click the button "Change label" it's also changes the color of my circle, it seems that it repaints the JFrame. And when I resize the window, the circle changes the color. I've experimented with the code a little to understand how it works. And I think that if something changes in the window it repaints all the frame. Am I right? Did I something wrong?
Thanks!
Please avoid long // comments because they make the lines too long; I have changed it to a /* comment */ which is a better length.
I am not sure why you are getting the change of colour. I think it has to do with the change of length of text in the left button. When it changes its length, the middle panel moves, and when it moves it is repainted. When it is repainted it calls the paintComponent method and that always chooses a new colour.
1. Define a class variable "circleColor" in the class "MyDrawPanel" and change it in the method "changeColor". Remove the code which changes the color from the method "paintComponent" to fix this problem.
2. In the inner class "ColorListner" of the class "TwoButtons" call the method "changeColor" which changes the variable "circleColor".
Sorry for my English =) I could make some mistakes.
As you found out, selecting a new color in the paintCompunent() method was a bad idea.
You really have little control as to when paintComponent() will be called. It will be called whenever there is a need to repaint the component - such as when its position in its parent changes, or its size changes, or when part of it is newly exposed, such as when another window that was on top of it is dismissed or moved (and backing store cannot automatically refresh the area), or shortly after anyone invokes the object's repaint().
For those reasons, your paintComponent() method should never make any changes in the visual display of your component - it should merely redraw it.
Other methods should be called to make changes in the object's state, and then those methods should call repaint() to ensure that paintComponent() then gets called to actually draw the changes.
One more thing: your paintComponent() method should always call super.paintComponent(g) as its first executable statement. Otherwise you may find that fragments of the previous drawing may still be showing, and the background may not be properly redrawn.
Thank you, Fred Kleinschmidt, for the explanation and your advice!
Thank you, Junilu Lacar. Yeah, there is a mistake ))) I should improve my English. =)