Delete and Backspace keys

Hello team,

I am coded a typewriter-like program with Processing but for some reasons it is not recognizing the BACKSPACE key and DELETE key, any idea of how I could make it work? I would like to avoid using arrays (having trouble wrapping my mind around it, and I use a String for this sketch anyway). I tried the if keyCoded function but it didn't work. I am new to Processing so don't mind the mess of my code^^ Thanks for your help!

Here is a sample of my code:

int pposx = 0;
int pposy = 0;
int posx = 0;
int posy = 0;
int x = 1430;
int y = 800;
int start = 0;
String text1 = " ";
boolean randomizer = false;

void setup() {
  size(1430, 800);
  background(255);
  smooth();
  strokeWeight(3);
  textSize(26);
}

void draw() {
  fill(0);
  text(text1, (x/2 - 50), (y/2 + 250), width, height);
  textSize(16);
  text("press Return to save your word and write a new one", (x/2 - 170), (y/2 + 300), width, height);
  textSize(26);
  if (randomizer) {
    for (int j = 0; j < 400; j++) {
      text1 += char(int(random(18, 126)));
    }
  }
}

void keyPressed() {
  println(key);
  pposx = posx;
  pposy = posy;

if (key == 'u') {
      posx = (x/2 + 175);
      posy = (y/2 - 200);
      text1 += key;
    }
 if (key == 'h') {
      posx =  (x/2 + 100);
      posy = (y/2 - 100);
      text1 += key;
    }
    if (key == 'm') {
      posx = (x/2 + 250);
      posy = y/2;
      text1 += key;
    }
    if (key == BACKSPACE) {
      posx = x/2;
      posy = (y/2 + 100);
      if (text1.length() > 0) {
        text1 = text1.substring(0, text1.length() - 1);
      }
    }
    if (key == DELETE) {
      background(255, 255, 255);
      text1 = " ";
      start = 0;
    }
    if (key == ENTER) {
      saveFrame("images/trace-####.jpg");
      // background(255, 255, 255);
      //text1 = " ";
      //start = 0;
    }
    line(pposx, pposy, posx, posy);
    println();
  }

Answers

  • I can't see why backspace won't work, it looks right.

    You aren't making a deletion happen with the delete, so, I'll look more into it.

  • if (key == BACKSPACE)
      text1= text1.substring(0, max(0, text1.length()-1));
    

    //this should work

  • Do the same for delete

  • Answer ✓

    Your program does recognize the BACKSPACE and DELETE keys and it does change text1 string accordingly. The problem is that the display is not being cleared in draw so if you type 'hum' this appears and when you press BACKSPACE it displays 'hu' but because the display is not cleared then 'm' is still displayed.

    add

    background(255);

    at the beginning of the draw() method it will hide the lines as well. The alternative is to draw a filled white box to erase the old text before displaying the new text.

Sign In or Register to comment.