日期:2014-05-20  浏览次数:20663 次

求教JFrame的问题
我想在JFrame中添加一个动态显示时间的组件,请问怎么实现.

------解决方案--------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.SimpleDateFormat;
public class Test
{
private JFrame f;
private ShowTime show;
private JButton btn;
public Test()
{
f = new JFrame();
Container c = f.getContentPane();
show = new ShowTime();
c.add(show, "Center ");
new Thread(show).start();
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new Test();
}

}


class ShowTime extends JPanel implements Runnable,ActionListener
{
boolean stop = true;
JLabel out = null;
private Date times = null;
private SimpleDateFormat matter = null;
JButton btn,btr;
public ShowTime()
{
out = new JLabel();
times = new Date();
btr = new JButton( "开始 ");
btn = new JButton( "停止 ");
add(out);
add(btn);
add(btr);
btn.addActionListener(this);
btr.addActionListener(this);
matter = new SimpleDateFormat( "HH时:mm分:ss秒 ");
out.setText( "现在时间: " +matter.format(times));
}

public void run()
{
while(true)
{
while(stop)
{
times = new Date();
out.setText( "现在时间: " +matter.format(times));
try{Thread.sleep(1000);}catch(Exception e){}
}
}
}

public void setStop(boolean b)
{
this.stop = b;

}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == btn)
setStop(false);

if(ae.getSource() == btr)
setStop(true);
}
}


乱写了一个,也实现你的要求了,哈哈