본문 바로가기

자바

쓰레드로 만든 시계

package pack.etc;


import java.awt.Button;

import java.awt.Font;

import java.awt.Frame;

import java.awt.Label;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.util.Calendar;


public class ThreadClock extends Frame implements ActionListener, Runnable{


private static final long serialVersionUID = 1L;

Label lblShow;

Boolean b = false;

Thread thread;

public ThreadClock() {

thread = new Thread(this); // 쓰레드 생성(this는 자기 자신을 쓰레드로)

lblShow = new Label("display time", Label.CENTER);

add("Center",lblShow);

Button button = new Button("Click");

add("South", button); // 아래쪽으로 정렬

button.addActionListener(this); // 버튼 리스너 장착(ActionListener 인터페이스의 override한 메소드인 actionPerformed이 호출된다.

setTitle("Thread Clock");

setBounds(200, 200, 600, 300);

setVisible(true);

addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

b = true;

System.exit(0);

}

});

}

//버튼 클릭시 실행

@Override

public void actionPerformed(ActionEvent e) {

// calenShow();

if(thread.isAlive()) return;

thread.start(); //run() 호출

}

@Override

public void run() {

while(true){

if(b == true) break;

calenShow(); // calenShow() 1초에 한번씩 계속 호출

try {

Thread.sleep(1000);

} catch (Exception e) {

// TODO: handle exception

}

}

}

//시간

private void calenShow(){

Calendar cal = Calendar.getInstance();

int y = cal.get(Calendar.YEAR);

int month = cal.get(Calendar.MONTH+1);

int date = cal.get(Calendar.DATE);

int hour = cal.get(Calendar.HOUR);

int min = cal.get(Calendar.MINUTE);

int sec = cal.get(Calendar.SECOND);

lblShow.setText(y +"YEAR " + month + "MONTH " + date +"DATE " + hour + "HOUR " + min + "MINUTE " + sec +"SECOND");

lblShow.setFont(new Font("궁서체", Font.BOLD, 16));

}

public static void main(String[] args) {

new ThreadClock();

}


}