A graphics class for viewing 2D scenes.
Many of the
Shape-subclasses specified in the
ProGAL.geom2d
package can be added to a
J2DScene object and are automatically
painted. For instance the following code creates a scene with 3 circles, two lines
indicating unit axis, and a text label.
J2DScene scene = new J2DScene();
scene.addShape(new LineSegment(new Point(0,0), new Point(1,0)), Color.BLACK);
scene.addShape(new LineSegment(new Point(0,0), new Point(0,1)), Color.BLACK);
scene.addShape(new Circle(new Point(0,0), 1), new Color(250,0,0,100), 0.05, false);
scene.addShape(new Circle(new Point(1,0), 0.2), Color.GREEN);
scene.addShape(new Circle(new Point(0,1), 0.2), Color.BLUE);
scene.addShape(new TextShape("(1,0)", new Point(1,0), 0.2), Color.BLACK);
JPanel canvas = scene.getCanvas();
JFrame frame = new JFrame();
frame.setSize(400,400);
frame.getContentPane().add( canvas );
frame.setVisible(true);
The
repaint() method must be called every time the position of
shapes has changed and the canvas should be updated. The pointers
to added shapes are stored, so subsequent changes will be visible on the canvas when
repaint() is called. The following example shows how to animate a circle
rotating around origo.
J2DScene scene = J2DScene.createJ2DSceneInFrame();
scene.addShape(new LineSegment(new Point(0,0), new Point(1,0)), Color.BLACK);
scene.addShape(new LineSegment(new Point(0,0), new Point(0,1)), Color.BLACK);
Circle c = new Circle(new Point(0,1), 0.2);
scene.addShape(c, Color.BLUE);
double t = 0;
while(true){
c.center().setCoord(0, Math.cos(t));
c.center().setCoord(1, Math.sin(t));
scene.repaint();
t+=0.01;
try {Thread.sleep(50);} catch (InterruptedException e) {}
}
As shown in this example, a static method is supplied for conveniently creating a frame
containing a scene-viewer.
Shapes are painted in the order they are inserted. The
addShape method has
support for border width and filling out a shape.