Search code examples
javaswingtimerjbuttonjtextfield

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.


Solution

  • 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.