Search code examples
javapause

Display my game over text for 2 seconds before going to my other code


I've tried to use Thread.sleep() but it pauses the program entirely before displaying game over very briefly. I've also tried to display the game over text before Thread.sleep() but I can't see it. Below is what I'm currently using.

try{
    Thread.sleep(2000);//pause for 2 seconds
    //display gameover
    gr.setColor(Color.WHITE);
    gr.setFont(new Font("arial", Font.BOLD, 50));
    gr.drawString("Game Over", 550, 300);
}
catch(InterruptedException e){
}

Solution

  • You could define a boolean showText for example, and then use it to determine, if you want to show text.

    public void runGameLogic() {
        showText = true;
        Timer t = new Timer(2000, (action) -> {
            showText = false;
        });
        t.setRepeats(false);
        t.start();
    }
    
    public void render() {
        if (showText) {
            gr.setColor(Color.WHITE);
            gr.setFont(new Font("Arial", Font.BOLD, 50));
            gr.drawString("Game Over", 550, 300);
        }
    }