4

While I am not doing some animation or drawing a very complicated graphics.
I need (sort of) double buffering for drawing several primitives. In the application, user enters name of Shape followed by related arguments and that shape is drawn on buffer, and then on screen. Eg of a command is RECT 100, 50, 200, 120.

For persistence, I can store all commands in list and in
public void paintComponent(Graphics g) of JPanel I draw them one by one.
But this is highly inefficient, because of iterating through list and using a hash map each time to call (or dispatch) the relevant shape-drawing-interface.

How and on what type of buffer can I draw? How can different methods draw on this buffer?

Additionally is there a convenient way to be able to undo previous draws with buffer? Or do I need to redraw on buffer each time a undo is done?

Thanks, I don't want full code, but relevant class names and small pseudocode is appreciated.

mKorbel
  • 108,320
  • 17
  • 126
  • 296
Vinayak Garg
  • 6,228
  • 10
  • 49
  • 78
  • Can you elaborate on your criteria for _efficient_? `List` typically suffices for thousands of shapes. – trashgod Feb 19 '12 at 08:32
  • @trashgod: There should not be flickering, and moreover drawing each time the application is switched, should not require to draw everything inside paintComponent. – Vinayak Garg Feb 19 '12 at 08:34
  • *"should not require to draw everything"* Research 'premature optimization'. – Andrew Thompson Feb 19 '12 at 10:59
  • @AndrewThompson: Sorry, but my last experience (of drawing breadboard) was not very good. So I got a little more worried. – Vinayak Garg Feb 19 '12 at 13:13
  • *"So I got a little more worried."* You should post a little [SSCCE](http://sscce.org/). – Andrew Thompson Feb 19 '12 at 13:37
  • @AndrewThompson: Well I had nothing to post as SSCCE, the above example I solved by using wxWidgets library with C++(so no point posting it) and this time around as you pointed out, it was _Research 'premature optimization'_. But I completely agree with you, I almost always try to post SSCCE, so as to make my question answerable. – Vinayak Garg Feb 20 '12 at 05:33

1 Answers1

6

JPanel is double buffered by default, so selecting and dragging are typically quite smooth. GraphPanel is a simple object drawing program that illustrates such operations on a List<Node>. A similar approach has been successfully used with thousands of nodes.

The details of implementing an undo strategy depend significantly on the desired behavior, but remove() and repaint() are effective.

Addendum: One common optimization for rendering large numbers of objects uses the flyweight pattern. JTable, JFreeChart and JGraph are examples. This simplified example illustrates the essential mechanism.

Community
  • 1
  • 1
trashgod
  • 196,350
  • 25
  • 213
  • 918