从JPanel删除非特定的JLabel

从JPanel删除非特定的JLabel

本文介绍了从JPanel删除非特定的JLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Java开发Black Jack游戏.我正在尝试与Swing合作,但现在我陷入了困境:我做了这个方法

I am currently working on a Black Jack game in Java.I am trying to work with Swing and I am stuck right now:I made this method

private void addImage(String path) {

        JLabel imgLabel = new JLabel();
        imgLabel.setIcon(new ImageIcon(getClass().getResource(path)));
        add(imgLabel);
        display.pack();

    }

我想要一个重置按钮在回合结束后重新启动,如何删除这些非特定的JLabel?我应该给他们一个标识符吗?如果是,怎么办?预先感谢.

I want to have a reset button to restart after a round ends, how can I remove these unspecific JLabels? Should I give them an identifier? If yes how?Thanks in advance.

推荐答案

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

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();
}

这篇关于从JPanel删除非特定的JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 11:30