Launch Create draw() setup() Run Extras |
Now, that you have seen your applet run. It's time to put something in (on) the applet. We will start with a rectangle that does not move, and then we'll make it move.
Some things to note about graphics in Java. The pixel in the upper left corner has coordinates x=0 and y=0. The pixel in the lower right corner has coordinates x=width-1 and y=height-1. Watch for how this affects how you work with a drawing canvas.
To draw a rectangle, you need:
- coordinates of the upper left corner of the rectangle (x,y)
- width of the rectangle in pixels
- height of the rectangle in pixels
Here are some examples. Try them and your own to see how the coodinate system works.
rect( 10, 5, 50, 30 ) ; // draw a rectangle with upper left corner at (10,5).
// The rectangle will be 50 pixels wide and 30 pixels high.
rect( x, y, width, height ) ; // assign values to the variables x,y,width,height first
int
variables named x
and y
. int x = (int) (Math.random()*getWidth());
int y = (int) (Math.random()*getHeight());
rect( x, y, 50, 30 ) ;
background(127)
at the start of your draw() method.Don't forget methods can call other methods. But, be warned that performance (refresh delays and other) will result if you try to do too much processing on each call to the draw() method.
To show figures and text on our applet, we will need to override (redefine) the setup() and draw() methods that we inherited from class PApplet. Continue with the next steps to get some ideas.
Launch Create draw() setup() Run Extras |
Your PApplet class uses the setup() method for code that must execute when the applet is started. Code in the setup() method executes just once at the start of the applet. It is kind of like a constructor for applets. Use it to initialize any items (data members) in your applet. You can also "draw" things here, but they will be drawn over by the draw method.
MovingRectangle
class. This method overrides (redefines) the setup() method that is inherited from PApplet.size( 100, 50 ) ; // 100 pixels wide by 5 pixels high
size( 200, 200 ) ; // 200 x 200 applet viewer canvas
size( 400, 50 ) ; // 400 x 50 pixels (looks like a banner -- think text scrolling)
background( 0 ) ; // sets background color to black
background( 255 ) ; // white
background( 127 ) ; // gray
Ready, set, draw! (in the next step).
fill( 255, 127, 0 ) ;
fill( 255, 0, 0 ) ;
fill( 0, 255, 0 ) ;
fill( 0, 0, 255 ) ;
Launch Create draw() setup() Run Extras
2015 Deb Deppeler