정리노트

[자바/java] thread 디지털 시계 본문

프로그래밍/Java

[자바/java] thread 디지털 시계

Rolen 2023. 2. 4. 17:28

Calendar 사용

1초마다 시간을 불러와서 label 변경

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



public class Q2 extends JFrame {
	JLabel label;

	class MyThread extends Thread {
		public MyThread() {
			label = new JLabel("aaa");
			label.setFont(new Font("Serif", Font.BOLD, 50));
			label.setBounds(100, 50, 400, 50);
			add(label);
		}
		public void run() {
			for (;;) {
				try {
					Calendar now = Calendar.getInstance();
					int h = now.get(Calendar.HOUR_OF_DAY);
					int m = now.get(Calendar.MINUTE);
					int s = now.get(Calendar.SECOND);
					String time = h+":"+m+":"+s;
					label.setText(time);
					Thread.sleep(1000);
				} catch(Exception e) {	}
			}
		}
	}
	Q2() {
		setTitle("Clock");
		setSize(400, 200);
		setLayout(null);
		
		new MyThread().start();
		
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	public static void main(String[] args) {
		Q2 q = new Q2();
	}

}
728x90