简体   繁体   中英

Update JTextFields text every 3 seconds after pressing button

So what I want to do is that when I press button JTextField text starts to update to new value every 3 seconds. I have tried Thread sleep metod, but it freezes whole program for the sleep time and after it is over textfields gets the latest input. So here is better explained example of what i am trying to do.

I press the JButton which puts the numbers in JTextFiel every 3 seconds as long as there is available values. I dont want it to append new text, just replace old with new. Anyone got ideas how I can do that? Thanks in advance.

You should use a javax.swing.Timer .

final Timer updater = new Timer(3000, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // update JTextField
    }
});
JButton button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        updater.start();
    }
});

The Timer will not block the Event Dispatch Thread (like Thread.sleep does) so it won't cause your program to become unresponsive.

You can't sleep in the EDT. You can either use a swingworker (better solution) or do something like this:

//sleep in new thread
new Thread (new Runnable() {
    public void run() {
        Thread.sleep(3000);
         //update UI in EDT
         SwingUtilities.invokelater(new Runnable()  {
              public void run() {updateYourTextHere();}
          });
    }
}).start();

You need to get 'the work' done on a separate thread. See some of the answers here: Java GUI Not changing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM