计时器的日期不断重复

时间:2014-02-18 20:10:03

标签: java date timer

好吧,我终于把我的代码带到了令人耳目一新的日期,但遗憾的是jlabel一遍又一遍地重复着。这是图片:

i.imgur.com/TxrTidC.png

我希望它只有一句话,但这句话会改变。

以下是代码:

package pro;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class pro6 extends JPanel {


Timer t;
JLabel l;
static JFrame f;

public pro6(final String sen){

    t = new Timer(1000, new ActionListener(){

        @SuppressWarnings("deprecation")

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            l = new JLabel(sen + new java.util.Date().toGMTString());   
            add(l);
            revalidate();

        }

    });

    t.start();

}
public static void main(String [] args){

    f = new JFrame("Date");
    f.setVisible(true);
    f.setSize(350, 150);
    f.getContentPane().setBackground(Color.CYAN);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pro6 obj = new pro6("The Date is: ");
    f.add(obj);
    f.revalidate();

}

}

1 个答案:

答案 0 :(得分:1)

您为每JLabel次迭代添加了新的Timer - 只需添加一个标签并使用setText进行更新

public class LabelUpdateApp {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame("Date");
                frame.getContentPane().setBackground(Color.CYAN);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                final JLabel label = 
                   new JLabel("-------------------------------------------------------------");
                frame.add(label);

                Timer t = new Timer(1000, new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        label.setText("The Date is: " + new Date());
                    }
                });

                t.start();
                frame.pack();
                frame.setVisible(true);
            };
        });

    }
}