应用Thread线程显示时钟在框架和标题
package com.hbsi;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.*;
class TestClock extends Thread{
JFrame jf=new JFrame("Clock");
JLabel clock=new JLabel("clock");
public TestClock(){
clock.setHorizontalAlignment(JLabel.CENTER);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(clock);
jf.setBounds(500,200,300,200);
jf.setVisible(true);
}
public void run(){
while(true){
clock.setText(getTime());
jf.setTitle(getTime());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public String getTime(){
Calendar c=Calendar.getInstance();
String time=c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DATE)+" ";
int h=c.get(Calendar.HOUR);
int m=c.get(Calendar.MINUTE);
int s=c.get(Calendar.SECOND);
String ph=h<10?"0":"";
String pm=m<10?"0":"";
String ps=s<10?"0":"";
time +=ph+h+":"+pm+m+":"+ps+s;
return time;
}
public static void main(String[] args) {
TestClock t=new TestClock();
t.start();
}
}
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.*;
class TestClock extends Thread{
JFrame jf=new JFrame("Clock");
JLabel clock=new JLabel("clock");
public TestClock(){
clock.setHorizontalAlignment(JLabel.CENTER);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(clock);
jf.setBounds(500,200,300,200);
jf.setVisible(true);
}
public void run(){
while(true){
clock.setText(getTime());
jf.setTitle(getTime());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public String getTime(){
Calendar c=Calendar.getInstance();
String time=c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DATE)+" ";
int h=c.get(Calendar.HOUR);
int m=c.get(Calendar.MINUTE);
int s=c.get(Calendar.SECOND);
String ph=h<10?"0":"";
String pm=m<10?"0":"";
String ps=s<10?"0":"";
time +=ph+h+":"+pm+m+":"+ps+s;
return time;
}
public static void main(String[] args) {
TestClock t=new TestClock();
t.start();
}
}