阻止JPanel重复添加ImageIcon

时间:2017-02-25 23:54:25

标签: java swing jframe jpanel jlabel

我在我的空闲时间创建一个国际象棋游戏,在用户执行动作(即移动一个棋子)之后,我更新窗口(JFrame)以显示新的棋子位置。但是,在我的更新函数中,我使用add(Component)函数将JLabel添加到JPanel。因此,每次有更新时,都会向组件添加多个JLabel,因为add()函数会堆叠JLabel。

    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(i).add(label)"每次调用时都会向JPanel添加多个JLabel。我试图将一个独特的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)

1 个答案:

答案 0 :(得分: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();
    }