Search code examples
javaswingsleep

How to delay an answer while not freezing the thread?


Simple question. Thread.sleep(x) freezes the entire code so even Buttons stay the way they are (pressed unpressed whatever)

I want to basicially click a button, "wait" for the computer to do it's thing for x amount of time and then output something.

public class bsp extends JFrame {
DrawPanel drawPanel = new DrawPanel();

public bsp() {
    setSize(600,600);
    JButton Hit = new JButton("Hit him");
    Hit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.out.println("I hit you back!");
            
        }
    });
    Hit.setSize(80, 30);
    Hit.setLocation(200, 400);
    add(Hit);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    add(drawPanel);
    setVisible(true);

}

private static class DrawPanel extends JPanel {

    protected void paintComponent(Graphics g) {
        
    }
}

public static void main(String[] args) {
    new bsp();

}

}

As you can see, the button "stays" pressed and the whole program is frozen. But I basicially want to simulate the "A.I." thinking before answering, without freezing everything.


Solution

  • Consider using a Timer to prevent main thread from freezing :

    import javax.swing.*;
    import java.awt.event.*;
    
            ActionListener task = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                 
                }
            };
            Timer countdown = new Timer(1000 ,task);
            countdown.setRepeats(false);
            countdown.start();
    

    where 1000 is the delay time in milliseconds and inside the actionPerformed function is where your code executes after the delay time set.