Text fields, strings, and chars

When we want to print messages with println we use text in “quotes”.
Technically we are passing a string as parameter. You can handle text as variable as long as you declare the proper type.

Declaration and assignment:

String name = "paolo";

Also strings:

 
String text1 = "666";
String text2 = "two words";
String text3 = "text on \nTwo lines";
String text4 = " "; //space
String text1 = "6$%#@# AaBb()";

Concatenation:

size(300, 300);
background(0);
String name = "paolo";
String lastName = "pedercini";
text(name + " " + lastName, 15, 30);
 
String nickName = "pizza";
String fullName = name + " \"" + nickName+"\" "+ lastName;
text(fullName, 15, 60);

Comparison:

size(300, 300);
background(0);
String name = "paolo";
 
if (name.equals("Paolo")) {
  text("Yes", 15, 30, 300);
}
else
{
  text("No", 15, 30, 300);
}

Upper case / lower case:

name = name.toUpperCase();
lastName = lastName.toLowerCase();

Char
Sometimes you want to manipulate single characters within a string. The variable type char is what you want to use.

String word = "HELLO WORLD";
 
void setup()
{
  size(300, 300);
  background(255);
  smooth();
}
 
void draw()
{
  background(255);
  fill(0);
 
  //read on character at time from position 0 to the last position: word.length()
  for (int i=0; i<word .length(); i++)
  {
    char letter = word.charAt(i);
 
    //text(letter, mouseX+i*20, mouseY+i*20);
    //note: in text() you cannot define the textfield 
    //size if you are using a char instead of a string
 
    //OR
    String part = word.substring(i, i+1);
    text(part, 40+i*20, 40+i*20, 100, 100);
 
  }
}

Formatting Text

You can change text color, it’s the same as the fill.

size(300,300);
background(0);
 
//text positioning
text("word", 15, 30);
//custom color
fill(0, 102, 153);
text("word", 15, 60);
//with alpha
fill(255, 255, 255, 100);
text("word", 15, 90);

You can use any font as long as you create a processing-friendly version.

Loading a font created with Processing -> tools -> Create font…

PFont font;
// The font must be located in the sketch's 
// "data" directory to load successfully
font = loadFont("CenturyGothic-32.vlw"); 
textFont(font, 32); 
text("word", 15, 50);

Alignment:

size(400, 200);
background(255);
fill(0);
textAlign(CENTER);
text("This text is centered.", width/2, 60); 
textAlign(LEFT);
text("This text is left aligned.", width/2, 100); 
textAlign(RIGHT);
text("This text is right aligned.", width/2, 140);
Posted in

Post a comment