2017-02-25 68 views
-1

我在空閒時間創建一個國際象棋遊戲,並且在用戶執行一個動作(即移動一個片段)後,我更新窗口(JFrame)以顯示新的片段位置。但是,在我的更新函數中,我使用add(Component)函數將JLabel添加到JPanel。因此,每次更新時都會將多個JLabel添加到組件,因爲add()函數會堆棧JLabels。防止JPanel反覆添加ImageIcon

BufferedImage img = null; 
    try{ 
     img = ImageIO.read(getClass().getResource(theTiles.get(i).getPiece().getImagePath())); 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 
    ImageIcon icon = new ImageIcon(img); 
    JLabel label = new JLabel(); 
    label.setIcon(icon); 

    //Here is where the error is: 
    theTiles.get(i).add(label); 
    label.repaint(); 

    this.window.validate(); 
    this.window.repaint(); 

因爲每當有更新時,該功能被稱爲「theTiles.get(ⅰ)。新增(標籤)」被添加在每次調用時多個的JLabel到的JPanel。我曾嘗試設置唯一的JLabel作爲類的私有變量,因此,它只是替換的JLabel,而不是當它需要更新,例如增加更多:

public class TilePanel extends JPanel{ 
    //JLabel variable 
    private JLabel someLabel = new JLabel(); 

    TilePanel(){ 
    //Add the component to the Panel 
     this.add(someLabel); 
    } 

    public Jlabel setLabel(JPanel newLabel){ 
    //setLabel function to use in the "update" function 
     this.someLabel = newLabel 
    } 


... 
//Use setLabel instead of add(Component) 
theTiles.get(i).setLabel(label); 

但是,這樣做會導致無圖像出現。我哪裏錯了? (注意:這是我第一次使用GUI)

+0

你已經改變了參考(以someLabel),但原來的標籤仍然在屏幕上(我不知道如何編譯),當更改標籤時,您需要刪除舊組件,然後添加新組件。 – MadProgrammer

+1

您也可以更改標籤的圖標 – MadProgrammer

回答

0

感謝MadProgrammer的提示;這裏要說的是我找到了解決辦法:

在我更新功能,我只要致電:

theTiles.get(i).setImage(); 

,並在我的課,我有以下:

public class TilePanel extends JPanel{ 
    //A JLabel for each tile 
    private JLabel theLabel = new JLabel(); 

TilePanel(int i, int j){ 
     //constructor add the Label to itself 
     this.add(theLabel); 


//A function to "setIcon" instead of using .add() multiple times 
public void setImage(){ 
    //assign in an icon 
    if (this.pieceAtTile != null){ 
      BufferedImage img = null; 
      try{ 
       img = ImageIO.read(getClass().getResource(this.pieceAtTile.getImagePath())); 
      }catch(IOException e){ 
       e.printStackTrace(); 
      } 
      ImageIcon icon = new ImageIcon(img); 
      this.theLabel.setIcon(icon); 
     } 
     else{this.theLabel.setIcon(null);} 
    theLabel.repaint(); 
    }