如何在JLabel上放置计时器以每秒更新一次

问题描述

| 我创建了一个游戏,并且在我的摆动GUI界面中想放置一个计时器。我现在的方式是在当前时间创建一个字段,并用with0ѭ取,该值在游戏开始时得到它的值。在我的游戏方法中,我将
System.currentTimeMillis()
-字段赋值;并告诉您游戏开始以来的当前时间。 不过,如何使它每秒更新一次让我们说,所以
JLabel
将具有:timePassed:0s,timePassed:1s,依此类推。请记住,我在任何时候都不会在游戏中使用线程。 编辑:谢谢大家的好心建议。我综合使用了您的答案,请给我一些反馈。 我将jlabel作为一个称为时间的字段。 (否则我无法处理)。
time = new JLabel(\"Time Passed:  \" + timePassed() + \" sec\");
    panel_4.add(time);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            time.setText(\"Time Passed: \" + timePassed() + \" sec\");
        }
    };
    Timer timer = new Timer(1000,actionListener);
    timer.start();
    

解决方法

        看一下摆动计时器类。它可以很容易地设置重复任务。     ,        这就是我将JLabel设置为随时间和日期更新的方式。
Timer SimpleTimer = new Timer(1000,new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        jLabel1.setText(SimpleDay.format(new Date()));
        jLabel2.setText(SimpleDate.format(new Date()));
        jLabel3.setText(SimpleTime.format(new Date()));
    }
});
SimpleTimer.start();
然后将其添加到您的主类中,并使用计时器更新jlabel1 / 2/3。     ,        
new Thread(new Runnable
{
    public void run()
    {
        long start = System.currentTimeMillis();
        while (true)
        {
            long time = System.currentTimeMillis() - start;
            int seconds = time / 1000;
            SwingUtilities.invokeLater(new Runnable() {
                 public void run()
                 {
                       label.setText(\"Time Passed: \" + seconds);
                 }
            });
            try { Thread.sleep(100); } catch(Exception e) {}
        }
    }
}).start();
    ,        在构造函数中写 ActionListener taskPerformer = new ActionListener(){
             @Override

            public void actionPerformed(ActionEvent evt) {
               jMenu11.setText(CurrentTime());
            }
        };

        Timer t = new Timer(1000,taskPerformer);
        t.start();
这个写出来的构造函数 公共字符串CurrentTime(){
       Calendar cal = new GregorianCalendar();
       int second = cal.get(Calendar.SECOND);
       int min = cal.get(Calendar.MINUTE);
       int hour = cal.get(Calendar.HOUR);
       String s=(checkTime(hour)+\":\"+checkTime(min)+\":\"+checkTime(second));
       jMenu11.setText(s);
       return s;

   }

   public String checkTime(int t){
String time1;
if (t < 10){
    time1 = (\"0\"+t);
    }
else{
    time1 = (\"\"+t);
    }
return time1;
}     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...