Text and image display

hello. Please help me! I must do this program: Add a rectangle in which the key-input is entered. When the ENTER-key is pressed, show the image corresponding with the entered digit (only the first one
if more than one digit is entered). Use the BACKSPACE-key to erase the input, so a new input can be given. I can’t keep the number on the screen when the image appears. Also, I don’t know how to make that part of image that corresponds to the number appear. I have attached the image with the result I should have received. Please, who can help me with any idea?
Digits

PImage Digits;
char d;
PFont fnt;
String s="Press any key and hit enter:";
void setup(){
  size(400,400);
  fnt= createFont("Arial",15);
  textFont (fnt);
  Digits= loadImage ("Digits.png");
}
void draw(){
  background (255);
  fill(0);
  d = key;
  textSize(60);
  text (d,35,110);
  textSize(30);
  textAlign(CENTER);
  text (s,width/2,30);
  noFill();
  rect(10,60,150,60);
  if (key==ENTER||key==RETURN) {
   image (Digits,width/2, height/2); }
   if (key==BACKSPACE) {
     return;
   }
  
}

my version

  • using a function keyPressed() (the function registers each key only once, the variable that you had registers it multiple times. Both have the same name.)
  • using a variable isSubmitted to store whether we want to show the Digits image
  • improved Backspace

// to have longer inputs, make "d" into a String 

PImage Digits;
char d=' ';
PFont fnt;
String s="Press any key and hit enter:";
boolean isSubmitted=false; 

void setup() {
  size(400, 400);

  fnt= createFont("Arial", 15);
  textFont(fnt);
  Digits= loadImage ("Digits.png");
}

void draw() {
  background (255);

  fill(0);
  textSize(60);
  text (d, 35, 110);

  textSize(30);
  textAlign(CENTER);
  text (s, width/2, 30);

  noFill();
  rect(10, 60, 150, 60);

  if (isSubmitted) {
    image (Digits, width/2, height/2);
  }
}

void keyPressed() {
  isSubmitted=false; // reset (restart after submitting)

  if (key==ENTER||key==RETURN) {
    isSubmitted=true; // submit 
  } else if (key==BACKSPACE) {
    d=' '; // looks empty
  } else if (key>='0'&&key<='9') {
    //only numbers are allowed 
    d=key;
  }
}
1 Like