利用runnable接口和Thread类 创建一个数字时钟小程序: import javax.swing.*; import java.awt.*; import java.lang.*; import java.util.*; public class ClockTest extends JFrame{ ClockPane clockPane; public ClockTest() { setTitle("Clock Program"); clockPane=new ClockPane(); //JPanel pane=new JPanel(); //pane.setLayout(new GridLayout(1,1,16,16)); //pane.add(clockPane); setContentPane(clockPane); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ClockTest test=new ClockTest(); test.pack(); test.setVisible(true); } } class ClockPane extends JPanel implements Runnable{ Thread thread; public ClockPane(){ if(thread==null) { thread=new Thread(this); thread.start(); } } @Override public void run() { // TODO Auto-generated method stub while(true) { repaint(); try{ Thread.sleep(1000); } catch(Exception e) { } } } @Override protected void paintComponent(Graphics arg0) { // TODO Auto-generated method stub Graphics2D comp2D=(Graphics2D)arg0; //comp2D.setBackground(Color.black); //comp2D.fillRect(0, 0, getSize().width, getSize().height); //comp2D.setFont(new Font("浪漫雅园",Font.BOLD,15)); comp2D.clearRect(0, 0, 666, 550); comp2D.setColor(Color.RED); Calendar cal=Calendar.getInstance(); comp2D.drawString(cal.getTime().toString(), 10, 50); } }