import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ContohTimer2 extends JFrame
implements ActionListener
{
private int jam = 0;
private int menit = 0;
private int detik = 0;
private int delay = 1000;
private Timer timer = null;
private Label label = new Label("00:00:00");
private Button btnStart = new Button("Start");
private Button btnStop = new Button("Stop");
private Panel panel = new Panel();
public ContohTimer2()
{
super("Contoh Timer #2");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100,100);
setSize(185,100);
btnStart.addActionListener(this);
btnStop.addActionListener(this);
panel.setLayout(new GridLayout(1,2));
panel.add(btnStart);
panel.add(btnStop);
label.setFont (new Font("arial",Font.BOLD,25));
label.setAlignment(Label.CENTER);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(label,BorderLayout.CENTER);
getContentPane().add(panel,BorderLayout.SOUTH);
setVisible(true);
timer = new Timer(delay, display);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == btnStart)
{
if (!timer.isRunning())
timer.start();
}
else
{
if (timer.isRunning())
timer.stop();
}
}
private ActionListener display = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String str1 = Integer.toString(jam);
String str2 = Integer.toString(menit);
String str3 = Integer.toString(detik);
if (jam < 10 ) str1 = "0" + str1;
if (menit < 10 ) str2 = "0" + str2;
if (detik < 10 ) str3 = "0" + str3;
label.setText(str1 + ":" + str2 + ":" + str3);
detik++;
if (detik == 60)
{
detik = 0;
menit++;
if (menit == 60)
{
menit = 0;
jam++;
if (jam == 24)
jam = 0;
}
}
}
};
public static void main(String[] args)
{
new ContohTimer2();
}
}