Java 如何将计时器放入 GUI 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22728794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:30:36  来源:igfitidea点击:

How to put timer into a GUI?

javaswinguser-interfacenetbeanstimer

提问by user2999509

I have a GUI with a form for people to fill up and I would like to put a countdown timer at the top right hand corner of the page

我有一个带有表单的 GUI 供人们填写,我想在页面的右上角放置一个倒数计时器

Heres the method for the timer to get the remaining time. Say my form class is FillForm and the timer method is found in Timer.

下面是定时器获取剩余时间的方法。假设我的表单类是 FillForm,定时器方法在 Timer 中。

How do I put a dynamic (constantly updating) timer inside of the GUI?

如何在 GUI 中放置动态(不断更新)计时器?

public String getRemainingTime() {
    int hours = (int)((this.remainingTime/3600000) % 60);
    int minutes = (int)((this.remainingTime/60000) % 60);
    int seconds = (int)(((this.remainingTime)/1000) % 60);

    return(format.format(hours) +  ":" +  format.format(minutes)+ 
          ":" +  format.format(seconds));       
}

GUI is built using NetBeans GUI builder.

GUI 是使用 NetBeans GUI 构建器构建的。

回答by Benjamin

Try This :

尝试这个 :

      import javax.swing.Timer; 
      Timer  timer=new Timer(1000,new ActionListener(){
         public void actionPerformed(ActionEvent e)
     {
        //code here 
     }
     });
     timer.start();
    //timer.stop()

Every one Seconds Timer Execute.

每隔一秒定时器执行一次。

   Try This Demo :

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;

class Counter {

private static int cnt;
static JFrame f;
public static void main(String args[]) {

 f=new JFrame();
 f.setSize(100,100);
 f.setVisible(true);


 ActionListener actListner = new ActionListener() {

 @Override

 public void actionPerformed(ActionEvent event) {
  cnt += 1;
 if(cnt%2==0)
 {
    f.setVisible(true);
 }
 else
 {
    f.setVisible(false);
 }
 }

};

Timer timer = new Timer(500, actListner);

 timer.start();
  }
 }

回答by Erwin Bolwidt

You should abstract your timer into a UI component. JLabelseems the most suited as it is a text that you want to display.

您应该将计时器抽象为 UI 组件。JLabel似乎最适合,因为它是您要显示的文本。

public class TimerLabel extends JLabel {
    // Add in your code for 'format' and 'remainingTime'.
    // Note that the first time that 'getText' is called, it's called from the constructor
    // if the superclass, so your own class is not fully initialized at this point.
    // Hence the 'if (format != null)' check

    public TimerLabel() {
        Timer timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                repaint();
            }
        });
        timer.start();
    }

    public String getRemainingTime() {
        int hours = (int) ((this.remainingTime / 3600000) % 60);
        int minutes = (int) ((this.remainingTime / 60000) % 60);
        int seconds = (int) (((this.remainingTime) / 1000) % 60);

        return (format.format(hours) + ":" + format.format(minutes) + ":" + format.format(seconds));
    }

    @Override
    public String getText() {
        if (format != null) {
            return getRemainingTime();
        } else {
            return "";
        }
    }

回答by Paul Samsotha

"Could i add this into a Swing.JPanel or something?"

“我可以将它添加到 Swing.JPanel 或其他东西中吗?”

Just put it in the constructor of your form class. Declare the Timer timer;as a class member and not locally scoped so that you can use the start()method like in a button's actionPerformed. Something like

只需将它放在表单类的构造函数中即可。将 声明Timer timer;为类成员而不是本地范围,以便您可以start()像在按钮的actionPerformed. 就像是

import javax.swing.Timer;

public class GUI extends JFrame {

    public Timer timer = null;

    public GUI() {
        timer = new Timer (500, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                if (timerGetsToZero) {
                    ((Timer)e.getSource()).stop();
                } else {
                    timeLabel.setText(getRemainingTime());
                }
            }
        });
    }

    private void startButtonActionPerformed(ActionEvent e) {
        timer.start();
    }
}