【问题标题】:automatic update jtextfield自动更新 jtextfield
【发布时间】:2012-09-07 11:41:05
【问题描述】:

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

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

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

Convert.getCheck:

    public String getCheck() {
        return check;
    }

【问题讨论】:

  • 你展示的这个while循环在哪里?在 main() 中,在 JFrame 中,在 JPanel 中?

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


【解决方案1】:

您想使用 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
       */
   }
 }

【讨论】:

  • 非常感谢!完美运行!
猜你喜欢
  • 2013-03-19
  • 2012-07-23
  • 1970-01-01
  • 2013-10-06
  • 2014-12-04
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多