Timer
You will need to have runnable going to have the timer update constantly. So implement Runnable and have the code at the bottom. Remember update gets called constantly.
See this page for more on time
// This class is to test animation
// Designed by Jeff Borland
// Date 11:16:06
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TestAnimation extends JApplet implements Runnable
{
int x=0;
long startTime = System.currentTimeMillis();
JTextField textField = new JTextField(20);
public void init()
{
Container screen = getContentPane();
screen.setBackground(Color.white);
screen.setLayout (new FlowLayout() );
screen.add(textField);
}
public void paint (Graphics g)
{
super.paint(g);
}
public void update()
{
long elapsedTimeMillis = System.currentTimeMillis()-startTime;
double elapsedTimeSec = elapsedTimeMillis/1000.0;
textField.setText(""+elapsedTimeSec);
}
/*********************************************************************************************/
/* BELOW IS FOR ANIMATION. THE ONLY THING THAT YOU NEED TO CHANGE IS DELAY */
int frame;
int delay=50; // this is the time of the delay in milliseconds.
Thread animator;
/**
* This method is called when the applet becomes visible on
* the screen. Create a thread and start it.
*/
public void start()
{
animator = new Thread(this);
animator.start();
}
/**
* This method is called by the thread that was created in
* the start method. It does the main animation.
*/
public void run()
{
// Remember the starting time
long tm = System.currentTimeMillis();
while (Thread.currentThread() == animator)
{
// Display the next frame of animation.
update();
try
{
tm += delay;
Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
}
catch (InterruptedException e)
{
break;
}
// Advance the frame
frame++;
}
}
/**
* This method is called when the applet is no longer
* visible. Set the animator variable to null so that the
* thread will exit before displaying the next frame.
*/
public void stop()
{
animator = null;
}
}
|