2017-02-25 64 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(); 
    }