方法之间的延迟

时间:2014-06-22 11:47:17

标签: java

我想在barresi和行动之间放置延迟,但它不起作用

public void actionPerformed(ActionEvent e) {//the button action 
  if(l<2){
  if(e.getActionCommand().equals("0")){
      bt[0][0].setIcon(icon[0]);// setting icon to a button
      s[0]=icon[0].getDescription();
      x=0;
      y=0;
      l++;
  }
  if(e.getActionCommand().equals("1")){
      bt[0][1].setIcon(icon[1]);
      l++;
      s[1]=icon[1].getDescription();
      dx=0;
      dy=1;
  }

  barresi();// this method 
}

public void barresi(){
    if(l==2) {  
      flag=true;
    }
    if(flag){
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
    action();
    }
}

public void action(){// i want to make delay here but when i click on a second button the image wont shown up it get null
  if(l>=2) {        
    if(s[0].equals(s[1])){
        System.out.println("OK");
        l=0;
    }
    else {
        bt[x][y].setIcon(null);
        bt[dx][dy].setIcon(null);
        l=0;
    }
  }
}

1 个答案:

答案 0 :(得分:1)

  

我希望将延迟放在barresiaction

之间

使用Swing Timer代替Thread.sleep,有时会挂起整个Swing应用程序。

请查看How to Use Swing Timers

只需启动Swing计时器并在2秒后调用的action()内调用actionPerformed()方法,如下面的示例代码所示。

示例代码:

Timer timer = new Timer(2000, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {            
        action();
    }
});
timer.setRepeats(false);
timer.start();

尝试这种方式:

public void barresi(){
    // all other stub of barresi method
    // action(); // remove it from here and move inside the Swing timer's actionPerformed method
    // start timer that will call the action method after 2 seconds
}