Use the java.swing.Timer class. The Timer needs a class that implements the ActionListener interface, so basically you write a class that implements that interface. In the actionPerformed method you just increment the seconds of a Calendar object, and use the DateFormat class to format the date for the text field. An example is probably easier than trying to explain it. Here's a JPanel that does what you need:
Code:
// TimeTestPanel.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
public class TimeTestPanel extends JPanel {
private static final int delay = 1000; // milliseconds
private static final int textFieldWidth = 20;
private JTextField textField = null;
private Timer timer = null;
public TimeTestPanel() {
textField = new JTextField( textFieldWidth );
timer = new Timer( delay , new TimerListener() );
add( textField );
timer.start();
}
class TimerListener implements ActionListener {
private Calendar calendar = null;
private DateFormat time = null;
public TimerListener() {
calendar = new GregorianCalendar();
time = DateFormat.getDateTimeInstance();
}
public void actionPerformed( ActionEvent event ) {
calendar.add( Calendar.SECOND , 1 );
textField.setText( time.format( calendar.getTime() ) );
}
}
}
You need to add the panel to a JFrame, so here's the JFrame:
Code:
// TimeTestFrame.java
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class TimeTestFrame extends JFrame {
public TimeTestFrame() {
Toolkit toolKit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolKit.getScreenSize();
Point frameLocation = new Point( screenSize.width/4 ,
screenSize.height/4 );
setSize( screenSize.width/2 , screenSize.height/2 );
setLocation( frameLocation );
setDefaultCloseOperation( EXIT_ON_CLOSE );
}
}
This is the main application class that creates the frame and panel, and adds the panel to the frame:
Code:
// TimeTest.java
public class TimeTest {
public static void main( String[] args ) {
TimeTestFrame frame = new TimeTestFrame();
TimeTestPanel panel = new TimeTestPanel();
frame.getContentPane().add( panel );
frame.show();
}
}