在解决“简单时钟”的问题的时候,遇到了时钟的时间更新的问题(也就是秒数自动跳动)。最初试着用一个循环来写的,如下:
private void refresh(){
pause();
GetTime time2 = new GetTime();
if(time2.second > second){
second = time2.second;
}
refresh();
}
但那时发现这个思路行不通,上网百了一下,建议都是用线程来实现,但是之前线程这一块没认真学,看来还真得补补了。
下面是百的一个数字时钟demo:
package test;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;
import java.util.Date;
import java.text.SimpleDateFormat;
public class ClockFrame extends JFrame implements Runnable,WindowListener
{
private Thread timer=null;
private JLabel jLabel=null;
private SimpleDateFormat sdf=null;
private boolean go;
public ClockFrame()
{
super( "时钟测试 ");
sdf=new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss ");
Date now=new Date();
jLabel=new JLabel(sdf.format(now));
getContentPane().add(jLabel,BorderLayout.CENTER);
addWindowListener(this);
setSize(200 ,100);
setLocation(300,200);
go=true;
timer=new Thread(this);
timer.start();
}
public void run()
{
while(go)
{
try
{
timer.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}finally
{
jLabel.setText(sdf.format(new Date()));
}
}
}
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e){
go=false;
setVisible(false);
System.exit(0);
}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public static void main(String args[])
{
new ClockFrame().setVisible(true);
}
};
测试通过