automatic update jtextfield

最后都变了- 提交于 2021-02-05 11:37:55

问题


Does anyone know how to update a jTextfield every 5 secondes? Automatic. So no userinput is required. It is used to update time in a textfield. This is what i tried but then my program freezes.

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

convert is a thread, i tried to throw an exception but failed, cause Eclise says Threads can't throw exceptions.

Convert.getCheck:

    public String getCheck() {
        return check;
    }

回答1:


You want to use a Swing Timer object. Here is a Oracle tutorial

To start with, you need to have your class implement the ActionListener interface. Inside of your class, you also need to implement an actionPerformed() method. Finally, you should start the timer in your main() function or somewhere

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

You would then implement your class like:

public class MyClass implements ActionListener
{
   ...

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


来源:https://stackoverflow.com/questions/12317426/automatic-update-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!