0

I have a class that inherits from JPanel. It is called DrawingPanel and in this class I draw lines and shapes using Graphics2D and I use the position of user's mouse to do some operations on these shapes.

The drawings in the panel can take a lot of space on screen (for instance I may draw lines from (-200, -300) to (2000, 1000)), so actually I only see a part of the drawings. That's why I would like to be able to move all things drawn in my panel with scrolling.

Is there a simple and elegant solution to do this, and that would not require too much changes in my code?

EDIT: Actually my problem is that I don't know an elegant way to have scrolling working in a JPanel with shapes drawn with Graphics2D. I tried to add my JPanel to a JScrollPane but it did not worked. Practically, what should I have to add to my code?

Fitz
  • 570
  • 1
  • 5
  • 23
  • "That's why I would like to be able to move all things drawn in my JPanel with scrolling." Is this not what scrolling does essentially? Move the viewport to different area of canvas? It's like physics relativity, the viewport moving is the same as the shapes moving. – thatidiotguy Nov 26 '12 at 15:36
  • I think the most elegant solution is to either: a) Start with a `BufferedImage` of defined size (range & scale) and display it in a label in a scroll pane or b) return a preferred size for the drawn panel that reflects the entire extent of the X/Y range, and transform (translate to fit) the graphics when drawn (then display it in a scroll pane). – Andrew Thompson Nov 26 '12 at 15:48
  • 1
    @AndrewThompson DooDoodle http://stackoverflow.com/questions/12683533/drawing-a-rectangle-that-wont-disappear-in-next-paint/12683632#12683632 would be a good example! :) – Branislav Lazic Nov 26 '12 at 15:51

1 Answers1

1

Put your drawing code in a separate method, called (for example) draw which takes 1 argument, a Graphics object.
In the paintComponent method you translate() the Graphics object according tonwhoch area of the drawing should be shown and then pass it into your draw method.

11684
  • 7,356
  • 12
  • 48
  • 71
  • It's a shame I did not think about this solution before :) It worked perfectly. Thanks. – Fitz Nov 26 '12 at 16:00