Search code examples
javaswingbufferjpanelgraphics2d

How to draw on a buffer with Undo capability?


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.


Solution

  • 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.