2012-11-28 19 views
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!你能告訴我爲什麼嗎?謝謝!爲什麼Thread.sleep()在Action中不起作用?

回答

1

actionPerformed()方法在事件派發線程中運行。重繪系統也是如此。如果你睡着了,你會推遲繪畫和其他一切。你永遠不應該睡在這個線程中。如果您想要延期塗料,請使用SwingWorkerjavax.swing.Timer啓動延期任務。

1

該動作由非線程執行,它也處理繪圖。你阻止這個線程。你什麼都看不到。遊戲結束。

這就是您不會阻塞或延遲事件傳播線程的原因。

尋找術語「事件調度程序線程」和「阻塞」,你會發現很多解釋血腥細節的東西。

1

ActionPerformed在事件分派器線程中運行。睡在那裏將會阻止UI的更新。

您可以使用Swing Timer來延遲操作。

相關問題