如何使用eclipse

时间:2015-11-06 18:37:30

标签: java eclipse countdown

这是问题。我不能在倒计时运行时点击按钮。我必须等到倒计时停止。我的问题是如何让倒计时在后台运行。或者任何建议。请帮助我!

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

}

2 个答案:

答案 0 :(得分:1)

我会在这里走出困境,因为我不做Java,但我要说你需要让应用程序是多线程的 - 你需要你的主线程不要被执行计时器的线程。使用回调创建一个新线程来增加计时器,关闭线程,然后在不再需要时终止线程。

答案 1 :(得分:0)

首先,您必须使用事件处理程序中的sleep()删除for()循环。在执行该代码时,您的用户界面将无响应。

尝试使用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();