import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.Color;
public class TimerSample1 extends JFrame {
private JPanel contentPane;
// timer inits
private JLabel label = new JLabel("00:00");
private static int minutes = 0, seconds = 0, milliseconds = 0;
private static Calendar date = Calendar.getInstance();
private static SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
private Timer timer;
// end of timer inits
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TimerSample1 frame = new TimerSample1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TimerSample1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("00:00:00");
lblNewLabel.setForeground(Color.RED);
lblNewLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 18));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(34, 23, 92, 32);
contentPane.add(lblNewLabel);
ActionListener timerListener = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
++milliseconds;
if (milliseconds >= 600) {
++seconds;
milliseconds = 0;
}
if (seconds >= 60) {
++minutes;
seconds = 0;
}
if (minutes == 1) {
timer.stop();
minutes = 0;
seconds = 0;
milliseconds = 0;
}
date.set(Calendar.SECOND, seconds);
date.set(Calendar.MINUTE, minutes);
lblNewLabel.setText(sdf.format(date.getTime()));
}
};
timer = new Timer(1, timerListener);
timer.start();
}
}