This code runs either as an application or as a Java applet.
TimerTest.java
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; /** This program shows a clock that is updated once per second. */ public class TimerTest extends JApplet { public JPanel panel; public Timer t; ActionListener listener; public TimerTest() { final int FIELD_WIDTH = 20; final JTextField textField = new JTextField(FIELD_WIDTH); panel = new JPanel(); //Container contentPane = frame.getContentPane(); //contentPane.setLayout(new FlowLayout()); panel.add(textField); listener = new ActionListener() { public void actionPerformed(ActionEvent event) { Date now = new Date(); textField.setText(now.toString()); } }; } public void startAnimation() { if (t == null) { final int DELAY = 1000; // milliseconds between timer ticks Timer t = new Timer(DELAY, listener); t.start(); } else if (!t.isRunning()) t.restart(); } public void stopAnimation() { t.stop(); } public void init() { getContentPane().add(panel); } public void start() { startAnimation(); } public void stop() { stopAnimation(); } public static void main(String[] args) { TimerTest test = new TimerTest(); JFrame frame = new JFrame(); Container contentPane = frame.getContentPane(); //contentPane.setLayout(new FlowLayout()); contentPane.add(test.panel); test.startAnimation(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }
Maintained by John Loomis, updated Sat Feb 24 12:12:25 2007