求教JFrame的问题

朝梦夕拾 2007-03-24 05:22:48
我想在JFrame中添加一个动态显示时间的组件,请问怎么实现.
...全文
161 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
朝梦夕拾 2007-03-24
  • 打赏
  • 举报
回复
厉害佩服死了.
frilly 2007-03-24
  • 打赏
  • 举报
回复
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);
}
}


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

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧