Tuesday, January 13, 2009

Digital Clock in Java

Oneday, my friend ask about how to make digital clock in java. It's like a timer, when the second has reach 60, the minute will be added by 1, when the minute reach 60, the hour will be added by 1.

This is the code. Hope this code will be useful not only for my friend, but also other people who need it.

import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.FlowLayout;

public class Jam extends JFrame {

private Timer timer;

int detik,menit,jam = 0;

JLabel lblDetik = new JLabel(”");
JLabel lblMenit = new JLabel(”");
JLabel lblJam = new JLabel(”");

public Jam()
{
setTitle(”Jam”);
setApplicationLayout();
setSize(150,75);
setLocationRelativeTo(null);
setVisible(true);
}

public static void main(String args[])
{
Jam jam = new Jam();
jam.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

class PuterJam extends TimerTask
{
public void run()
{
detik++;
if(detik==60)
{
detik=0;
menit++;
}
if(menit==60)
{
menit=0;
jam++;
}
if(detik<10) lblDetik.setText(”0″+detik);
else lblDetik.setText(”"+detik);

if(menit<10) lblMenit.setText(”0″+menit+” : “);
else lblMenit.setText(”"+menit+” : “);

if(jam<10) lblJam.setText(”0″+jam+” : “);
else lblJam.setText(”"+jam+” : “);
}
}

public void setApplicationLayout()
{
timer = new Timer();
timer.schedule(new PuterJam(), 0,1*1000);
setLayout(new FlowLayout());
add(lblJam);
add(lblMenit);
add(lblDetik);

}

}

Best regards,

Deny Sutani

No comments:

Post a Comment