Test3.java

Download: java1.zip.

This example illustrates the use of a Timer to do animation. The Timer constructor takes two arguments: the delay in milliseconds and the ActionListener that will respond to the Timer's ActionEvents. For the second argument, an object of the inner class TimerHandler is created. This object calls JPanel's repaint function to redraw the screen.

This example also illustrates the ability for a Java program to run either as an applet or as a standalone application, by including the static function main as a member of the subclass that extends JApplet.

The example here modifies Test2 by rotating one of the points about the origin.


// Test3.java
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.JApplet;

 class Panel3 extends JPanel
{
    Vec2 pt[];
    private Timer myTimer;
    Panel3()
    {
	pt = new Vec2[3];
	pt[0] = new Vec2(0.1,0.1);
	pt[1] = new Vec2(0.5, 0.8);
	pt[2] = new Vec2(0.8,0.1);
	System.out.println("Vec2's:" + pt[0] + pt[1] + pt[2]);
    }
    public void startAnimation()
    {
	if (myTimer == null)
	{
	    myTimer = new Timer(50,new TimerHandler() );
	    myTimer.start();
	}
	else if (!myTimer.isRunning()) myTimer.restart();
    }
    
    public void stopAnimation()
    {
	myTimer.stop();
	pt[1].set(0.5,0.8);
    }
	
    private class TimerHandler implements ActionListener
    {
	public void actionPerformed(ActionEvent actionevent)
	{
	    repaint();
	}
    }
    public void paintComponent(Graphics g)
    {
	super.paintComponent( g );
	Vec2.xoffset = getWidth()/2;
	Vec2.yoffset = getHeight()/2;
	int resx = getWidth()/4;
	int resy = getHeight()/3;
	Vec2.Resolution = (resx<resy? resx: resy);
	if (myTimer.isRunning()) pt[1].rotate(5);
	for (int i=0; i<pt.length; i++) pt[i].draw(g);
	Vec2 origin = new Vec2(0,0);
	int [] iv = origin.convert();
	g.drawLine(iv[0]-2,iv[1]-2,iv[0]+2,iv[1]+2);
	g.drawLine(iv[0]-2,iv[1]+2,iv[0]+2,iv[1]-2);
    }
}

public class Test3 extends JApplet
{
    Panel3 panel;
    public void init() {
	panel = new Panel3();
	getContentPane().add(panel);
    }
    public void start() {
	panel.startAnimation();
    }
    public void stop() {
	panel.stopAnimation();
    }

    public static void main(String args[] )
    {
	Panel3 panel = new Panel3();
	JFrame application = new JFrame("Test3");
	application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	application.add(panel);
	application.setSize(200,200);
	application.setVisible(true);
	panel.startAnimation();
    }
}


Results

To run as an application, use the java command in a console window:

java Test3

To run as an applet, include the following tag in an html file:

<applet code="Test3.class" width=300 height=300> </applet>


Maintained by John Loomis, updated Sun Jan 28 11:27:19 2007