An Eclipse project setup for Processing is assumed.
Some Processing methods are intended to be called by a programmer, including size
, background
, and rect
. Other Processing methods are intended to be overriden by a programmer, including draw
, keyPressed
, and mouseClicked
. (Overriding a method means replacing it with a new version.) Both types of methods are found in the PApplet
class.
Using classes with Processing in Eclipse requires special handling to ensure access to Processing methods. Only the class with the main
method extends PApplet
. Extending PApplet
in other classes appears to resolve some compile time errors; however, the code is unlikely to work as intended.
Example with 2 classes
Face
class (without main
method)
package multipleClasses;
import processing.core.PApplet;
public class Face
{
private PApplet parent;
private int centerX, centerY;
public Face(PApplet p, int cX, int cY)
{
parent = p;
centerX = cX;
centerY = cY;
}
public void drawSelf()
{
parent.fill(0, 155, 255);
parent.ellipse(centerX, centerY, 450, 450);
parent.fill(255);
parent.ellipse(centerX - 100, centerY - 100, 50, 50);
parent.ellipse(centerX + 100, centerY - 100, 50, 50);
parent.arc(centerX, centerY + 100, 150, 100, PApplet.radians(0), PApplet.radians(180));
}
}
The instance variable parent
stores a reference of type PApplet
. The Faces
constructor accepts a reference to the (one and only) PApplet
object that exists for this execution of the Processing sketch.
All instance methods of Processing intended to be run by a programmer are prefixed with parent.
. For example parent.fill(255)
sets the fill color to white.
Static methods of Processing intended to be run by a programmer are prefixed with PApplet.
. For example PApplet.radians(180)
returns the radian value for 180 degrees.
Attempting to override Processing methods such as draw
and keyPressed
within Face
will not work. It is possible to write a method named keyPressed
within Face
; however, it will not be run automatically when a key is pressed.
ManyFaces
class (with main
method)
package multipleClasses;
import processing.core.PApplet;
public class ManyFaces extends PApplet
{
private Face f1, f2, f3;
public static void main(String[] args)
{
PApplet.main("multipleClasses.ManyFaces");
}
public void settings()
{
size(1500, 500);
}
public void setup()
{
f1 = new Face(this, 300, 585);
f2 = new Face(this, 750, 250);
f3 = new Face(this, 1250, 400);
}
public void draw()
{
f1.drawSelf();
f2.drawSelf();
f3.drawSelf();
}
}
When each Face
object is constructed, this
is passed as the first argument to the Face
constructor.
Additional resources
More on using classes with Processing demonstrates:
- handling mouse presses with more than 1 class,
- using more than 2 classes.