2015-11-06 99 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