为什么Thread.sleep()不能在Action中执行?

时间:2012-11-28 22:08:16

标签: java jbutton actionlistener thread-sleep

public void actionPerformed(ActionEvent e) {
        String sp1="Player 1's turn. ";
        String sp2="Player 2's turn. ";
          System.out.println("Mouse entered for rating " + index);  //helps me track the cards
           ori=new ImageIcon(getClass().getResource(index+1+".png")); //set the image to the card

        ori.setDescription("ori");  //It's weird that I cannot directly flip the card, so I used this method to flip the cards.
        tail.setDescription("tail");//http://stackoverflow.com/questions/13557561/the-method-about-imageicons-does-not-work


        if (((ImageIcon) bt[index].getIcon()).getDescription()=="ori")
            bt[index].setIcon(tail);
         else
            bt[index].setIcon(ori);

        count++;

       System.out.printf("Action Performed %d times \n",count);
         if(count==1){  //if the card is clicked for once, the card should not flip and the index is stored in record.
           record=index;
           countS++;

       }
       String turnS=Integer.toString(countS);//parse the int and printout the turn 
     //  text3.setText(sp1+"This is turn "+turnS);
       if(count==2){
           int match1=record/4;   //Since every four cards have the same rank, I used this to get the rank very easily
           int match2=index/4;
          if(match1==match2&&record!=index){  //compare the two cards clicked
              p1++;
              score1=Integer.toString(p1);   
              text1.setText("Player 1: "+score1);  //display the score
              text3.setText(sp2+"This is turn "+turnS);
              bt[index].setEnabled(false);//remove the cards that match
              bt[record].setEnabled(false);
          }
          if(record==index){
              text3.setText(sp2+"This is turn "+turnS);//designed for the situation that the user clicks the same card
          }
          if(match1!=match2){//designed for the situation that the two cards do not match
           //time.schedule(taskFlip1,500);//delay the flip so that the user can see the cards
           //time.schedule(taskFlip2,500);


              try{   **//This part is problematic!**

                  Thread.currentThread().sleep(4000);
                  flip(index);
                  flip(record);


                }
                catch(Exception ie){

                }
              }
          text3.setText(sp2+"This is turn "+turnS);


       }

当我点击按钮时,该按钮应该更改ImageIcon。没有睡眠,它工作正常。但是在我添加睡眠后,当我点击按钮时,程序暂停而不更改ImageIcon!你能告诉我为什么吗?谢谢!

3 个答案:

答案 0 :(得分:1)

动作由同样处理绘图的线程执行。你阻止这个线程。你什么也看不见。游戏结束。

这就是为什么你不能阻止或延迟事件调度线程的原因。

搜索术语“事件调度程序线程”和“阻止”,您会发现许多解释血腥细节的内容。

答案 1 :(得分:1)

ActionPerformed在事件调度程序线程中运行。睡在那里将阻止UI更新。

您可以使用Swing Timer来延迟操作。

答案 2 :(得分:1)

actionPerformed()方法在事件调度线程中运行。重绘系统也是如此。如果你睡觉,你就会推迟绘画,等等。你永远不应该睡在这个线程中。如果您想要延迟绘制,请使用SwingWorkerjavax.swing.Timer来启动延迟任务。