自动更新jtextfield

时间:2012-09-07 11:41:06

标签: java swing concurrency jtextfield event-dispatch-thread

有没有人知道如何每5秒更新一次jTextfield?自动。因此不需要用户输入。它用于更新文本字段中的时间。这是我尝试过但我的程序冻结了。

while(true){
                        Thread.sleep(1000);
                        txtCheck.setText(convert.getCheck());
                        System.out.println("Ja");
                        }

convert是一个线程,我试图抛出异常但失败了,因为Eclise说线程不能抛出异常。

Convert.getCheck:

    public String getCheck() {
        return check;
    }

1 个答案:

答案 0 :(得分:3)

您想使用Swing Timer对象。这是Oracle tutorial

首先,您需要让您的类实现ActionListener接口。在您的类中,您还需要实现actionPerformed()方法。最后,你应该在main()函数或某个地方启动计时器

timer = new Timer(5000, MyClass);
timer.setInitialDelay(pause);
timer.start();

然后您将实现您的类:

public class MyClass implements ActionListener
{
   ...

   void actionPerformed(ActionEvent e) {
       /*
        This is called every time the timer fires, put your code here
       */
   }
 }
相关问题