Putting text in a rectangle

edited August 2015 in Questions about Code

If I use rect() to draw a rectangle and want to put the text " TEST " inside

text(" TEST ", 20,20);

Text does not appear in rectangle.


  • You may try out function text() w/ more arguments:

    Be aware that it all depends on the PFont used and its metrics like textSize(), textWidth(), etc.

  • Answer ✓

    I'll bet it's because the rectangle and the text are the same color. Try inserting fill(0) between the two lines above.

  • That did it, so now I know I have to set fill color for rect() then text() so now I have a draw loop. When mousePressed() I want to redraw rect as red with black text inside. So I have a testdone variable. Its initialized to 1 so draw just loops testing for testdone to change from 1 to 0. Mouse press ocurrs, in mousePressed() i redraw rect() with fill red and text().

    But no matter where I place it in draw , or mousepressed() it only flashes red and then back to blue.

    So i put if in draw to change fill from to red for testdone==0, still , just a flash.

    I am really struggling with WHEN things get executed. Why doesn't putting the redraw in the mousePressed() loop , which only gets executed once , cause it to change to a red rect() and stay until testdone set back to 1 in draw loop.

    The flow is:

    int testdone=1;

    setup(){ size(1000,600) }

    draw() {

    if(testdone==1)} fill(0,0,255) // blue box with black TEST inside rect(x,y,w,h) fill(0); text("TEST",100,100);}

    if (testdone==0){ fill(255,0,0) // red box with black TEST inside rect(x,y,w,h) fill(0) text("TEST",100,100);

    //execute loops to process image loadPIxels();

    [ loop code ]




    mousepresssed() {

    if (testdone ==1){ testdone=0; } }

  • The reference says rect () will draw a rectangle but it doesn't seem to be executed when i call it, it gets updated in draw loop according to what rules?

  • I do a fill(255,0,0) and rect(x,y,w,h); in mousePressed() and println("text"); statement just before and after "test" prints to let me know i am in the mousePressed() loop but rect() never changes! so when does it get drawn to the screen again?

    1. Please see How to format code and text
    2. You can use the boolean type for your testdone variable, it would be clearer.
    3. Don't draw in mousePressed method, set up variables there and draw in draw(), depending on these variables.
Sign In or Register to comment.