且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从JPanel删除非特定的JLabel

更新时间:2023-12-05 07:59:22

您可以通过创建包含所有标签的列表来做到这一点.

You can do this by creating a list that contains all the labels.

List<JLabel> labelsList = new ArrayList<JLabel>();

确保在addImages方法之外声明此内容,以便可以在其他方法中对其进行访问.然后,每次创建图像标签时,您都可以使用以下方法将其添加到列表中:

Make sure to declare this outside of the addImages method so that it can be accessed in other methods. Then, every time an image label is created you can add it to the list by using:

labelsList.add(imgLabel)

要移除卡,您可以实现一种重置方法,该方法循环遍历标签列表并移除每个组件,并确保也将其从labelsList中移除:

To remove the cards, you could implement a reset method that loops through the labels list and removes each component, making sure to also remove it from the labelsList:

public void resetLabels()
{
    for (JLabel label : labelsList) {
        remove(label);
        labelsList.remove(label);
    }
}

我认为学习收藏会很有帮助在这种情况下,请继续努力!

I think learning about collections would be very helpful in this case, keep up the good work!

仔细查看后,您不应在遍历循环时修改列表,而是:

After a closer look, you shouldn't modify the list as you go through the loop, instead:

public void resetLabels()
{
    for (JLabel label : labelsList) {
        remove(label);
    }
    labelsList.clear();
}