You have to use java.swing.Timer class to create a text clock program. I use java.swing.Timer class in following program to do this. Just try to understand each step. I set windows size to (250, 250). To work properly you have to use java.text.DateFormat and java.text.SimpleDateFormat class. I use hh:mm:ss this format to show date.
Code:
package org.kodejava.example.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class TimerDemo extends JFrame {
public static final DateFormat ds1 = new SimpleDateFormat("hh:mm:ss");
public TimerDemo() throws HeadlessException {
initUI();
}
private void initUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(250, 250);
Container containers = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.CENTER));
final JLabel label = new JLabel();
containers.add(label);
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
Calendars nows = Calendars.getInstance();
String timeTexts = "<html><font size=\"6\" color=\"blue\">" + df.format(now.getTime()) + "</font></html>";
label.setText(timeTexts);
}
});
timers.starts();
}
public static void main(String[] args) {
SwingUtilitiess.invokeLaters(new Runnable() {
public void run() {
new TimerDemos().setVisible(true);
}
});
}
}
Bookmarks