So, I am drawing a graphic in a JPanel object using Grahics2D.
The JPanel is placed in a JScrollPane for the cases when my graphic is bigger than the window.
But after I draw my graphic the JPanel‘s size does not change and I cannot scroll to see the rest of my graphic, so I locate the lowest and most left points and set the size manually in the method that does the drawing (method is called drawTrack()).
When I switch windows or do something else that makes the JPanel to be drawn again, my graphic disappears, so I rewrote paint(), repaint(), validate(), invalidate() methods and in there I invoke the drawTrack() method to draw my graphic on every possible case of redrawing the JPanel.
The problem is that when the JPanel invokes one of the methods that do the redrawing I invoke drawTrack() in them, which after redrawing my graphic sets the size manually so that I can scroll the JScrollPane and see my whole graphic. But when I invoke setSize() method on the JPanel that makes it to be redrawn again, which means to invoke drawTrack() and so on and so on.
The scroll bars appear because the size is correct but it creates an infinite loop that redraws my graphic over and over. And if I don’t invoke the setSize() method my JPanel gets default size so it can fit in the JScrollPane‘s viewport and thus I cannot scroll it to see my graphic.
Any suggestions?
So, I am drawing a graphic in a JPanel object using Grahics2D . The
Share
When you resize a JPanel you stimulate a repaint, and so if you change the size in a paint or paintComponent method or a method called in either of these methods, it makes sense to me that you are at risk of causing an infinite loop.
Solution: Don’t resize anything in a paint or paintComponent method. That method is just for painting and nothing else. Instead if you want to set the size of your JPanel, override its getPreferredSize() method.
Here’s a “colorful” example: