Home > Blockchain >  Is it possible to automatically perform an event in java continuously?
Is it possible to automatically perform an event in java continuously?

Time:10-22

For example, I want a JTextfield to display different random numbers continuously with start, stop and resume buttons. What is the possible solution to automatically update the JTextField continuously when the start button is pressed? I tried using while loop inside the start button's action listener but it just makes the button stuck in the while loop. This is the part of the code that I tried.

startButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            while(true){
                textField.setText(String.valueOf(random.nextInt()));
            }
        }
    });

CodePudding user response:

Read Concurrency in Swing.

You can use a javax.swing.Timer to change the text of the JTextField.

A tiny example:

public class TimerExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->{
            JTextField field = new JTextField(10);

            Timer timer = new Timer(100, e->{
                field.setText(String.valueOf(Math.random()));
            });
            timer.start();

            JOptionPane.showMessageDialog(null,field);
        });
    }
}

If you use while(true) in the Thread that runs the UI (this thread is called EDT - event dispatch thread), the thread won't be able to handle events since it is stucked inside the while loop.

  • Related