Search code examples
javaeclipsecountdown

how to make countdown running in background using eclipse


this is the problem.i cant't click the button while countdown is running.i have to wait until countdown stop.My question is how to make countdown running in background.or any suggestion.please help me !

    public static void main(String args[]){
        scrbutton myWindow = new scrbutton();  //set window design
        myWindow.setSize(300,70);
        myWindow.setVisible(true);
        myWindow.setResizable(false);

    }

    public scrbutton() {

        super("Clicker");     //Title
        setLayout(new FlowLayout());
        addWindowListener(this);
        add(kotak);
        add(kotak2);                         //add and design you components
        add(kotak3);
        add(enter);
        enter.addActionListener(this);
        kotak.setText("0");
        kotak2.setText("Times remaining: 60");
        kotak.setEditable(false);
        kotak2.setEditable(false);
        kotak3.setEditable(false);

    }


    public void actionPerformed(ActionEvent e)    //What will run through the program?
    {   



    click++;
    kotak.setText("\r"+click);                              //display number of click
    if (click >=10){
        kotak3.setText("You Win!");
        enter.setEnabled(false);
    }else{
        kotak3.setText("try again");
        }   

    for(int x=60; x>=0; x--) 

         {System.out.print(x+"\r");             // use print than println if you use (/r). 
         try {Thread.sleep(100);}               // 1000ms=1second thus its sleep(delay) 1 second between each iteration. 
         catch (InterruptedException e1){}      

         }
    }


 public void windowClosing(WindowEvent e) {
     dispose();
     System.exit(0);
}

public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}

}


Solution

  • I'm going to go out on a limb here, as I don't do Java, but I'd say you need to have the application be multi-threaded - you need your main thread not to be blocked by the executing thread of the timer. Create a new thread with callback to increment the timer, kick the thread off, then terminate the thread when no longer needed.