Harold
Harold

Reputation: 345

How do you convert thread.sleep to javax.swing.timer?

Is there a way to easily convert thread.sleep to javax.swing.timer?

The reason why I would need to do this, is to stop the user-interface from freezing when you press a button, so that you can implement a pause button.

Code Example:

btnStartTiming.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent arg0) {
                try{
                         inputA = Double.parseDouble(txtEnterHowLong.getText()); //Changes double to string and receives input from user
                        }catch(NumberFormatException ex){                        
                        }

            while (counter <= inputA){
                    txtCounter.setText(counter + ""); 
                    try {
                        Thread.sleep(1000);
                    } catch(InterruptedException ex) {
                        Thread.currentThread().interrupt();   
                    }
                    System.out.println(counter);
                    counter++;
                    }
        }
    });

Upvotes: 0

Views: 1037

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 209012

  • Put the java.swing.Timer in your constructor. You can use the button to .start() the timer.
  • Also instead of the while, you can add an if statement in the timer code check when to .stop()

Something like this

int delay = 1000;
Timer timer = new Timer(delay, null);

public Constructor(){
    timer = new Timer(delay, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            if (counter >= inputA) {
                timer.stop();
            } else {

                // do something
            }
        }
    });
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            timer.start();
        }
    });

}

Upvotes: 2

dic19
dic19

Reputation: 17971

Some tips:

Upvotes: 3

Related Questions