A program that allows to type in text. Whenever you hit enter, it will print it into the console.
Features:
- Can enter letters from the “acceptableInput” string
- use arrow keys (LEFT and RIGHT) or click on the text to edit text
- use BACKSPACE / DELETE to remove letters
- ENTER to erase input and print it into the console
- flexible interface
- blinker
String input = "";
int buffer = 20, minWidth = 200, cursorLocation = 0, lastInput = 0, resumeBlinkAfter = 300;
String acceptableInput = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789.,-+ !?<>()'$%&/[]#{}~=:;" + char('"');
void setup() {
size(200,100);
textAlign(3,3);
surface.setResizable(true);
}
void draw() {
background(0);
fill(255);
text(input,width/2,height/2);
textSize(20);
text("Input:",width/2,height/4);
stroke( ((second()%2 == 0 || lastInput + resumeBlinkAfter > millis())? color(255,0,0,255) : color(255,0,0,0)));
line(width/2-textWidth(input)/2+textWidth(getShorterString(input,cursorLocation)), height/2 - 10, width/2-textWidth(input)/2+textWidth(getShorterString(input,cursorLocation)), height/2+10);
}
void keyPressed() {
if(key == ENTER) {
cursorLocation = 0;
println(input);
input = "";
} else if (key == BACKSPACE) {
String prefix = getShorterString(input,cursorLocation-1);
String suffix = getAfterText(input,cursorLocation);
input = prefix+suffix;
cursorLocation= ((cursorLocation < 0)? 0 : cursorLocation-1);
} else if(key == DELETE) {
String prefix = getShorterString(input,cursorLocation);
String suffix = getAfterText(input,cursorLocation+1);
input = prefix+suffix;
} else {
for(int i = 0; i < acceptableInput.length(); i++) {
if(key == acceptableInput.charAt(i)) {
String prefix = getShorterString(input,cursorLocation), suffix = getAfterText(input,cursorLocation);
input += key;
input = (prefix + key + suffix);
cursorLocation+=1;
lastInput = millis();
}
}
}
if(keyCode == LEFT) {
cursorLocation = ((cursorLocation < 1)? 0 : cursorLocation - 1);
} else if(keyCode == RIGHT) {
cursorLocation = ((cursorLocation > input.length()-1)? input.length() : cursorLocation + 1);
}
resizeWindow();
if(input.length() > 4) {
}
}
void mousePressed() {
float beginTextX = width/2 - textWidth(input)/2;
for(int i = 0; i < input.length()+1; i++) {
if(mouseX > textWidth(getShorterString(input,i-1)) + beginTextX && mouseX < textWidth(getShorterString(input,i)) + beginTextX) {
cursorLocation = i-1;
}
}
}
String getShorterString(String text, int len) {
String newText = "";
if(len < 0) {
return("");
}
for(int i = 0; i < len && i <= text.length(); i++) {
newText += text.charAt(i);
}
return(newText);
}
String getAfterText(String text, int begin) {
if(begin < 0 || begin > text.length()) {
return("");
}
String newText = "";
for(int i = begin; i < text.length(); i++) {
newText+= text.charAt(i);
}
return(newText);
}
void resizeWindow() {
float setWidth = textWidth(input) + 2*buffer;
setWidth = ((setWidth > minWidth)? setWidth : minWidth);
surface.setSize(floor(setWidth),height);
}