I have a JScrollPane
displaying (as its viewport view) MyPanel
, a subclass of JPanel
.
MyPanel
implements custom painting by overloading paintComponent
. The total size of the displayable content of MyPanel
is generally quite wide (meaning 50x to 200x wider than the size of the JScrollPane
viewport) and using a Timer
, I scroll horizontally to view different sections of the underlying MyPanel
. I also allow using the scroll bar thumb to manually seek to a specific area of MyPanel
.
In my paintComponent
implementation I am currently finding the portion of MyPanel
that is currently visible in the view port using JViewport#getVisibleRect
, and just painting that portion each time the view port position is changed.
This works fine - but I end up repainting a significant percentage of the visible portion of MyPanel
over and over as the timed scrolling only moves the view port 1/50 of the view port width at a time. Also, I generally end up scrolling through the entire horizontal extent of MyPanel
, so I have to paint it all at least once anyway.
That leads me to think about painting the entire contents of MyPanel
just once (to a BufferedImage
?) and then letting JScrollPane
(or JViewport
) handle clipping and blitting only the needed area of the BufferedImage
.
Intuitively this seems to me to be the most efficient way of handling this, and something that would be relatively common.
As I investigate the Swing tutorials and other sources, I learn that Swing is already double buffered. If I try to force this on my own brute-force, independent of Swing functionality, it sounds like I'll end up with triple-buffering.
I haven't found the recipe (if it exists) to exploit JScrollPane
to do this for me.
Is there an example available, or some direction as to how to do this (if possible)?