스레드를 이용하여 디지털 시계 만들기
import javax.swing.*;
import java.awt.*;
import java.util.Calendar;
public class DigitalClockTest extends JFrame{
private JLabel label;
class MyThread extends Thread{
public void run() {
Calendar now = Calendar.getInstance();
int hrs = now.get(Calendar.HOUR_OF_DAY);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
String time = hrs+":"+min+":"+sec;
for(;;) { //계속 반복
label.setText(Integer.toString(hrs)+":"+(Integer.toString(min)+":"+(Integer.toString(sec))));
sec++;
if(sec==60) { //60초가 되면 분으로 넘어감
sec=0;
min++;
}
if(min==60) { //60분이 되면 시간으로 넘어감
min=0;
hrs++;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
label.setText(time);
}
}
}
public DigitalClockTest() {
setTitle("디지털시계");
setSize(400,150);
label = new JLabel();
label.setFont(new Font("Serif", Font.BOLD, 100));
add(label);
setVisible(true);
(new MyThread()).start();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DigitalClockTest t = new DigitalClockTest();
}
}