Notice
Recent Posts
Recent Comments
Link
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Archives
Today
Total
관리 메뉴

흑설이의 세상사는 이야기

JAVA 쓰레드를 이용해서 디지털 시계만들기 본문

JAVA)

JAVA 쓰레드를 이용해서 디지털 시계만들기

kuroyuki 2017. 9. 15. 18:16

 

digital clock.exe

완성본 입니다.

 

src :

import java.awt.*;
import javax.swing.*;
import java.util.Calendar;

public class DigitalClock extends JFrame{
 public DigitalClock() {
  setTitle("Digital Clock");
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setSize(500,150);
  setVisible(true);
  
  Container c = getContentPane();
  c.setLayout(new FlowLayout());
  
  JLabel TimeLabel = new JLabel();
  TimeLabel.setFont(new Font("Gothic",Font.ITALIC,70));
  c.add(TimeLabel);
  
  TimerThread th = new TimerThread(TimeLabel);
  th.start();
 }
 public static void main(String args[]) {
  new DigitalClock();
 }
}

class TimerThread extends Thread {
 JLabel timerLabel;
 public TimerThread(JLabel Label) {
  timerLabel = Label;
 }
 
 public void run() {
  Calendar time = Calendar.getInstance();
  int hour = time.get(Calendar.HOUR_OF_DAY);
  int minute = time.get(Calendar.MINUTE);
  int sec = time.get(Calendar.SECOND);
  
  while(true) {
   timerLabel.setText((Integer.toString(hour))+"시"+(Integer.toString(minute))+"분"+(Integer.toString(sec))+"초"); //int n에서 문자를 가져온 후 그 값의 객체화
   sec++;
   if(sec==60) { //60초가 되면 분으로 넘겨줌
    sec = 0;
    minute++;
   }
   if(minute==60) {//60분이 차면 시간으로 넘겨줌
    minute = 0;
    hour++;
   }
   try {Thread.sleep(1000);} //1s=1000ms|thread를 잠시 멈추고 ms단위로 그만큼 지난후 동작시킨다.
   catch(InterruptedException e) {return;} //안 깨어나는 경우가 있을까봐 try-catch문을 사용함.
  }
 }
}

Comments