0
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!你能告诉我为什么吗?谢谢!

4

3 回答 3

1

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

这就是您不应阻塞或延迟事件调度程序线程的原因。

搜索术语“Event Dispatcher Thread”和“blocking”,你会发现很多解释血淋淋的细节的东西。

于 2012-11-28T22:12:09.243 回答
1

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

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

于 2012-11-28T22:12:11.263 回答
1

actionPerformed()方法在事件分派线程中运行。重绘系统也是如此。如果你睡着了,你就是在推迟绘画,以及其他一切。你永远不应该在这个线程中睡觉。如果您想要延迟绘制,请使用SwingWorkerjavax.swing.Timer开始延迟任务。

于 2012-11-28T22:13:03.653 回答