2

I am trying to convert from processing to processingjs and have something I just can't understand.

In processing the following code returns whichever letter you type in, though in processingjs it just comes back with the keycode value but I need the letter not the code.

String name="";

void setup(){
 size(200,200);
}

void draw(){  
}

void keyPressed() {
  if(key==ENTER) {
  name="";
}
else {
 name+=key;
 println(name);
 }
}

3 Answers3

1

After hours of searching and the above answer I've found the answer here peepproject.com/forums/thread/266/view more eloquently than I. Basically the solution is to convert the int to a char() before constructing a String and putting it into an array.

Sastrija
  • 3,284
  • 6
  • 47
  • 64
  • 1
    the processing way `name += char(key);`, the java way `name +=(char)key;` or the processing.js way `name += char(key);` or the javascript way (to mix with processing js) `name += String.fromCharCode(key);" – JAMESSTONEco Oct 22 '12 at 19:51
0

You need to use the char conversion function in Processing and Processing.js:

http://processingjs.org/reference/char_/

The reason why it's displaying as a number is this line:

char x = 97; //supposed to be an 'a'

Does a cast in Java (may require char x = (char)97).

However in processing.js it is executed as:

var x = 97;

Since javascript has dynamic typing. You therefore need to explicitly force type casts such as from int->char.

Arcymag
  • 1,037
  • 1
  • 8
  • 18
  • After hours of searching and the above answer i've found the answer here http://peepproject.com/forums/thread/266/view more eloquently than I. Basically the solution is to convert the int to a char() before constructing a string and putting it into an array. – Grubbypandas Oct 21 '12 at 21:26
0

Instead of name += key, try name += key.toString().

Processing's println automatically does type conversion for you, so the char value of PApplet.key gets printed as a letter. JavaScript string concatenation works differently; the integer value of PApplet.key will be appended to the string as an integer and will not automatically be converted to a string. You have to do it manually.

ericsoco
  • 24,913
  • 29
  • 97
  • 127