Java 防止JPanel重复添加ImageIcon
我在空闲时间创建一个国际象棋游戏,在用户执行一个动作(即移动棋子)后,我更新窗口(JFrame)以显示新棋子的位置。但是,在我的update函数中,我使用add(Component)函数将jlabel添加到JPanel。因此,每次更新时,都会向组件添加多个JLabel,因为add()函数会堆叠JLabelJava 防止JPanel重复添加ImageIcon,java,swing,jframe,jpanel,jlabel,Java,Swing,Jframe,Jpanel,Jlabel,我在空闲时间创建一个国际象棋游戏,在用户执行一个动作(即移动棋子)后,我更新窗口(JFrame)以显示新棋子的位置。但是,在我的update函数中,我使用add(Component)函数将jlabel添加到JPanel。因此,每次更新时,都会向组件添加多个JLabel,因为add()函数会堆叠JLabel BufferedImage img = null; try{ img = ImageIO.read(getClass().getResource(theTile
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();
因为每当有更新时都会调用此函数,“thetitles.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)感谢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();
}
您已经更改了引用(到someLabel),但原始标签仍在屏幕上(我不确定这将如何编译),更改标签时,您需要删除旧组件,然后添加新组件。您也可以只更改标签的图标