2015-07-10 63 views
2

我正在嘗試製作自己的簡單記憶遊戲,並且我有一個實現ActionListener接口幷包含一些從JButton繼承的Tiles的JPanel。幾乎所有的工作都很好,除了按鈕被點擊作爲第二個事實,它不會像它應該做的那樣改變它的圖標。但是,當我點擊匹配的兩個瓷磚時,它們仍然翻轉並且正常。當我點擊第一個按鈕時,它會翻轉並按下第二個按鈕,但是如果沒有添加ActionListener,那麼它的匹配行爲就像一個按鈕。我想着用PropertyChangeListener解決這個問題,但不知道如何。當按下記憶遊戲時,JButton不會更改圖標

這是方法我的JPanel:

@Override 
    public void actionPerformed(ActionEvent e){ 

     Tile tile = (Tile)e.getSource(); 

     if(tilesFlipped < 2){ 
      tile.flip(); 
      flippedTiles[tilesFlipped++] = tile; 

      if(tilesFlipped == 1){ 
       return; 
      } 

      if(flippedTiles[0].equals(flippedTiles[1])){ 
       tilesFlipped = 0; 
       return; 

      } else { 
       try { 
        Thread.sleep(1000); 
        for(int i = 0; i < 2; i++){ 
         flippedTiles[i].flipBack(); 
        } 
       } catch (InterruptedException e1) { 
       } 
      } 
      tilesFlipped = 0; 
     } 

    } 

這是我的瓷磚類:

private class Tile extends JButton { 
    String photoPath; 
    ImageIcon photo; 

    Tile(int i){ 
     photoPath = String.format("/home/stn/Desktop/p/9-%d.jpg", i); 
     setPreferredSize(new Dimension(150, 150)); 
     this.setBackground(Color.cyan); 
     this.photo = new ImageIcon(photoPath); 
    } 

    public void flip(){ 
     this.setIcon(photo); 
     this.setBackground(Color.white); 
    } 

    public void flipBack(){ 
     this.setBackground(Color.cyan); 
     this.setIcon(null); 

    } 

    public String getPhotoPath(){ 
     return photoPath; 
    } 

    @Override 
    public boolean equals(Object o){ 
     return o instanceof Tile && ((Tile)o).getPhotoPath().equals(photoPath); 
    } 
    @Override 
    public int hashCode(){ 
     return photoPath.hashCode(); 
    } 

} 
+0

它看起來像tilesFlipped總是會是0-我們沒有所有的代碼在這裏,但這看起來像一個錯誤。 – dbillz

+0

@dbillz tilesFlipped在遊戲開始時爲0,然後似乎正常工作(當按下按鈕等於最後點擊一個按鈕時,我沒有阻止這種情況,但無論如何改變按鈕圖標應該工作) – stz

+0

更新,問題幾乎肯定是造成的通過Thread.sleep()方法,但我不知道爲什麼以及如何解決這個問題。什麼可能是Thread.sleep()的最佳選擇? – stz

回答

2

使用Swing Timer,而不是Thread.sleep(...)。理解Thread.sleep(...)使當前線程進入睡眠狀態,此處爲Swing 事件調度線程EDT,這將使您的整個GUI進入睡眠狀態,凍結您的應用程序。擺動計時器將執行一個或重複操作而不捆綁EDT。例如:

public void actionPerformed(ActionEvent e) { 

    Tile tile = (Tile) e.getSource(); 

    if (tilesFlipped < 2) { 
     tile.flip(); 
     flippedTiles[tilesFlipped++] = tile; 

     if (tilesFlipped == 1) { 
      return; 
     } 

     if (flippedTiles[0].equals(flippedTiles[1])) { 
      tilesFlipped = 0; 
      return; 

     } else { 
      Timer timer = new Timer(1000, new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       for (int i = 0; i < 2; i++) { 
        flippedTiles[i].flipBack(); 
       } 
       tilesFlipped = 0; 
      } 
      }); 
      timer.setRepeats(false); 
      timer.start(); 
     } 
    } 

} 
+0

非常感謝你,這完全解決了我的問題,實際上我終於用擺動計時器固定了它,但解決方案並不那麼順利。 – stz