Search code examples
javaswingjscrollpanesimulatorcircuit

Using JScrollPane for scroll and really big and zoomed custom drawing


I am working in a personal project. a circuit simulator if you are interested. In my project I use a JPanel to draw my content. I can move it and zoom it using AffineTransformations. Each time paint() is called I draw the area of the drawing the user is supposed to see. The drawing can be very big (i have no restrictions on how big it can be). I use a Rectangle that tracks the visible area of my drawing and the draws it in the JPanel graphics2d.

Now I want to add scrollbars to move my viewport I think that JScrollPane can be useful. I have seen a lot of threads talking about using a JPanel with JScrollPane to scroll simple content. The first when you look is this one, but I do not like this solutions because the scrollpane really scrolls the JPanel. And in all the examples I am supposed to draw ALL THE PANEL AREA!. I only draw the visible area of the panel because it is very time consuming.

So, my question is: How can I use the scrollpane to move my custom viewport and reflect the changes (i do not want to scroll the jpanel I use for drawing)? Or should I use a JPanel and two simple JScrollbars?

I can not find a simple guide to implement the Scrollable interface from scratch. All tutorials start from a JPanel or a JLabel

Thanks for any advice!!

(sorry for my english)


Solution

  • Assuming that you're using paintComponent to paint your contents, you can inspect the Graphics clip bounds. This will tell you what area needs to be repainted, when viewed from a JScrollPane, the scrollpane will reduce the area that it wants to be repainted to meet it's viewable area.

    What's important to remember about this is, the area represented by the clipping rectangle is the "new" or "changed" area, not the viewable area, this is done for optimisation reasons...