2015-11-06 101 views
0

這是problem.i不能點擊按鈕,而倒計時running.i必須等到倒計時停止。我的問題是如何讓倒計時運行在background.or任何建議,請幫助我!如何使倒計時運行在後臺使用eclipse

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) {} 

}

回答

1

我要去這裏走出去的肢體,因爲我不是做Java的,但我要說,你需要有應用程序是多線程的 - 你需要您的主線程不會被定時器的執行線程阻塞。創建一個帶回調的新線程來遞增定時器,關閉線程,然後在不再需要線程時終止線程。

+0

我使用線程和它的完美運行!謝謝bro – hizers

0

首先,您必須從事件處理函數中使用sleep()函數刪除()循環。在執行代碼時,您的用戶界面將無法響應。

嘗試使用javax.swing.Timer設置一個每1秒觸發一次的計時器。然後在定時器的事件處理程序中做任何構成「倒計時」的事情。

int delay = 1000; //milliseconds 
    ActionListener taskPerformer = new ActionListener() { 
     public void actionPerformed(ActionEvent evt) { 
      // do whatever constitutes counting down here 
     } 
    }; 
    new Timer(delay, taskPerformer).start(); 
+0

我使用線程和它的完美運行!謝啦兄弟 – hizers