Undo and Redo Button

// Press CTRL+Z to undo, CTRL+SHIFT+Z to redo 
// We need these to know if CTRL/SHIFT are pressed
boolean controlDown = false;
boolean shiftDown = false;
Undo undo;
void setup() {
 size(500, 500);
  undo = new Undo(10);
void draw() {
  // Our two line drawing program
  if (mousePressed)
    line(mouseX, mouseY, pmouseX, pmouseY);
void mouseReleased() {
  // Save each line we draw to our stack of UNDOs
void keyPressed() {
  // Remember if CTRL or SHIFT are pressed or not
  if (key == CODED) {
    if (keyCode == CONTROL)
      controlDown = true;
    if (keyCode == SHIFT)
      shiftDown = true;
  // Check if we pressed CTRL+Z or CTRL+SHIFT+Z
  if (controlDown) {
    if (keyCode == 'Z') {
      if (shiftDown)
  // Check if we pressed the S key
  if (key=='s') {

I found this code for Undo and Redo… But redo doesn’t seem to work and when I put them as a button, and none of them seem to work which is really confusing. If some as tried them as buttons and they both work please let me know what you did!!


Your code, as posted, never sets controlDown or shiftDown back to false when they are released. That’s probably the problem.

can you show me what you mean if possible, this is a fairly new code to me since I was given this?

It’s very concerning that you do not understand code you were given.

When a key is pressed, the keyPressed() function runs once.
The value in keyCode is the name of the key pressed.
That value does not change inside keyPressed()!

If I press down the Shift key, what does keyPressed() do?
If I press down the Control key, what does keyPressed() do?
Answer: That’s right - it sets the appropriate boolean to true.

Does that change ever get reverted?!? That is, when is controlDown or shiftDown ever set back to false?
Hint: It’s never set back to false!

You might think about adding a keyReleased() function…

1 Like

oh Alright I will defenitly look into this code.

Thanks, Much appreciated

1 Like