I have a JPanel on which I’ve painted four rectangles. The color for each of these rectangles is selected at random. The colors should change only when the user clicks on a particular rectangle.
The problem is, while a user is resizing the window, everything on the JPanel is ‘repainted’ repeatedly. This causes the rectangles to rapidly change color.
Ideally, I would need the colors of the rectangles to stay the same during a resize. Otherwise, I could also manage with a solution where the JPanel is repainted only once after a resize has been completed.
Do you have any general ideas on how I could implement this? I feel like it would have been a lot easier if there was a onStartResize and onFinishResize callback method in ComponentListener.
Thanks!
This example may serve to illustrate the violation adduced by @kleopatra. As a component is resized, the event dispatch mechanism helpfully invokes
repaint()for you. If you change the state of what you’re rendering, say inpaintComponent(), you’ll see it cycle rapidly. In the example below, the bottom row flickers as you resize, while the top row remains unchanged.Addendum:
AnimationTestis a related example that takes advantage of this effect to perform animation in aComponentAdapter.