1

I am trying to create a little drawing pad in one of my programs. This is the class:

class DrawPad extends JComponent {

Image image;
Graphics2D graphics;
int currentX, currentY, oldX, oldY;

public DrawPad() {
    setDoubleBuffered(false);        
    addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            oldX = e.getX();
            oldY = e.getY();
        }
    });

    addMouseMotionListener(new MouseMotionAdapter() {
        @Override
        public void mouseDragged(MouseEvent e) {
            currentX = e.getX();
            currentY = e.getY();
            if (graphics != null) {
                graphics.drawLine(oldX, oldY, currentX, currentY);
            }
            repaint();
            oldX = currentX;
            oldY = currentY;
        }           
    });
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (image == null) {
        image = createImage(getSize().width, getSize().height);
        graphics = (Graphics2D) image.getGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        clear();
    }
    g.drawImage(image, 0, 0, null);
}

public void clear() {
    graphics.setPaint(Color.white);
    graphics.fillRect(0, 0, getSize().width, getSize().height);
    graphics.setPaint(Color.black);
    repaint();
}

public void undo() {
    // restore previous graphics here
}

public void red() {
    graphics.setPaint(Color.red);
    repaint();
}

public void black() {
    graphics.setPaint(Color.black);
    repaint();
}

public void magenta() {
    graphics.setPaint(Color.magenta);
    repaint();
}

public void blue() {
    graphics.setPaint(Color.blue);
    repaint();
}

public void green() {
    graphics.setPaint(Color.green);
    repaint();
}

}

I add it to a JPanel. The drawing itself works fine. Now I would like to implement an undo method. I thought I could just copy the current graphics2D object into a backup variable and on click of the undo-button I would replace the current object with the backup object. Unfortunately that didn't work.

I tried the following:

In the mousePressed method I assigned the current value of graphics to the backup variable.

addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        graphicsBackup = graphics.create();
        oldX = e.getX();
        oldY = e.getY();
    }
});

and in the undo method I tried to assign the reference of the backup variable to the original object.

public void undo() {
    graphics = graphicsBackup;
    repaint();
}

In my second try I worked with the AffineTransform Object. I called getTransform in the keyPressed method to get the current state and then setTransform in the undo method. That didn't work either. Do you have any suggestions how it could work?


SOLUTION: (added some additional methods for background etc.)

class DrawPad extends JComponent {

private Image image;
private Image background;
private Graphics2D graphics;
private int currentX, currentY, oldX, oldY;
private final SizedStack<Image> undoStack = new SizedStack<>(12);

public DrawPad() {
    setDoubleBuffered(false);
    addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            saveToStack(image);
            oldX = e.getX();
            oldY = e.getY();
        }
    });

    addMouseMotionListener(new MouseMotionAdapter() {
        @Override
        public void mouseDragged(MouseEvent e) {
            currentX = e.getX();
            currentY = e.getY();
            if (graphics != null) {
                graphics.drawLine(oldX, oldY, currentX, currentY);
            }
            repaint();
            oldX = currentX;
            oldY = currentY;
        }
    });
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (image == null) {
        image = createImage(getSize().width, getSize().height);
        graphics = (Graphics2D) image.getGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        clear();
    }
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}

public void clear() {
    if (background != null) {
        setImage(copyImage(background));
    } else {
        graphics.setPaint(Color.white);
        graphics.fillRect(0, 0, getSize().width, getSize().height);
        graphics.setPaint(Color.black);
    }
    repaint();
}

public void undo() {
    if (undoStack.size() > 0) {
        setImage(undoStack.pop());
    }
}

private void setImage(Image img) {
    graphics = (Graphics2D) img.getGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.setPaint(Color.black);
    image = img;
    repaint();
}

public void setBackground(Image img) {
    background = copyImage(img);
    setImage(copyImage(img));
}

private BufferedImage copyImage(Image img) {
    BufferedImage copyOfImage = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
    Graphics g = copyOfImage.createGraphics();
    g.drawImage(img, 0, 0, getWidth(), getHeight(), null);
    return copyOfImage;
}

private void saveToStack(Image img) {
    undoStack.push(copyImage(img));
}

public void red() {
    graphics.setPaint(Color.red);
    repaint();
}

public void black() {
    graphics.setPaint(Color.black);
    repaint();
}

public void magenta() {
    graphics.setPaint(Color.magenta);
    repaint();
}

public void blue() {
    graphics.setPaint(Color.blue);
    repaint();
}

public void green() {
    graphics.setPaint(Color.green);
    repaint();
}
}

SizedStack:

public class SizedStack<T> extends Stack<T> {

private final int maxSize;

public SizedStack(int size) {
    super();
    this.maxSize = size;
}

@Override
public Object push(Object object) {
    while (this.size() > maxSize) {
        this.remove(0);
    }
    return super.push((T) object);
}
}
1
  • 1
    I cannot add an UndoManager to a Graphics2D object, to the image nor to the JComponent. Where would I have to add it?
    – Moh-Aw
    May 12, 2014 at 12:11

1 Answer 1

5

I implemented a drawing program myself a while back. Here's how I implemented undo/redo:

I had two stacks. 'Undo' stack and 'redo' stack. Every time the user draws something, this is what I did:

  1. Before applying the graphics drawn to the image, I save the image to the 'undo' stack.
  2. After applying the graphics drawn, I save the image again to the 'undo' stack.

For example, if the user wants to draw a line, I save the current image to the stack before applying the line to the image. And after applying the line, I save it again to the stack.

When the user presses 'undo', I simply pop the top image from the 'undo' stack, and draw it to the screen. Then I put it in the 'redo' stack.

When the user presses 'redo', the top image in the 'redo' stack is popped and applied to the drawing area, and put on top of the 'undo' stack (the reverse operation).

EDIT: In order to push the image onto the stack (without all the objects in the stack being references to the same object), you need to first copy the image to a new image. Something like this (might be inaccurate on the details):

void saveToStack(BufferedImage img){ // makes a copy of img and puts on stack.
    BufferedImage imageForStack = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
    Graphics2D g2d = imageForStack.createGraphics();
    g2d.drawImage(img, 0, 0, null);
    undoStack.push(imageForStack);
}

Hope this helps.

4
  • It did indeed help. I created a Stack<Image> but how would I create a new instance of my variable "image" to push it on the stack. Right now the stack is full of references to the same object.
    – Moh-Aw
    May 12, 2014 at 14:26
  • worked perfectly. added solution to question. I only implemented the 'undo' part though.
    – Moh-Aw
    May 14, 2014 at 9:03
  • If you wanted to limit the undo steps to not run out of memory you probably would use an array queue and dequeue or overwrite the states added earlier when the limit is reached.
    – xoxox
    Jan 28, 2017 at 15:25
  • How memory efficient is this approach? Feb 17, 2023 at 15:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.