Im adding buttons for a game but when removing the button in a loop it will only get rid of one button even though i added them in the same way
我为游戏添加按钮但是当在循环中删除按钮时,即使我以相同的方式添加按钮,它也只会删除一个按钮
for(int i=0 - 1; i < 4 ; i++) {
panelButtonsub.remove(buttonBlankItems);
}
panelButtonsub.setLayout (new GridLayout (intLayout,intLayout));
revalidate();
repaint();
2 个解决方案
#1
If you want to remove all the buttons in the panel you can use:
如果要删除面板中的所有按钮,可以使用:
panel.removeAll();
If you want to remove the first 4 buttons in the panel you can use:
如果要删除面板中的前4个按钮,可以使用:
for (int i = 0; i < 4, i++)
panel.remove(0);
If you are trying to remove a certain type of component from the panel then you need to start at the end to remove the components:
如果您尝试从面板中删除某种类型的组件,则需要从最后开始删除组件:
int components = panel.getComponentCount();
for (int i = components - 1; i >= 0; i --)
{
Component c = panel.getComponent(i);
if (c instance of BlankButton)
panel.remove(i);
}
Where BlankButton
is the component you created to represent the extra space by using panel.add( new BlankButton(...) )
.
其中BlankButton是您创建的用于通过使用panel.add(new BlankButton(...))来表示额外空间的组件。
If you are trying to do something else then you need to clarify your question.
如果您正在尝试做其他事情,那么您需要澄清您的问题。
#2
You must have distinct instances for each buttonBlankItems
button. I guess that you are adding the same button 5 times and then you are trying to remove them.
您必须为每个buttonBlankItems按钮设置不同的实例。我猜你要添加相同的按钮5次,然后你试图删除它们。
#1
If you want to remove all the buttons in the panel you can use:
如果要删除面板中的所有按钮,可以使用:
panel.removeAll();
If you want to remove the first 4 buttons in the panel you can use:
如果要删除面板中的前4个按钮,可以使用:
for (int i = 0; i < 4, i++)
panel.remove(0);
If you are trying to remove a certain type of component from the panel then you need to start at the end to remove the components:
如果您尝试从面板中删除某种类型的组件,则需要从最后开始删除组件:
int components = panel.getComponentCount();
for (int i = components - 1; i >= 0; i --)
{
Component c = panel.getComponent(i);
if (c instance of BlankButton)
panel.remove(i);
}
Where BlankButton
is the component you created to represent the extra space by using panel.add( new BlankButton(...) )
.
其中BlankButton是您创建的用于通过使用panel.add(new BlankButton(...))来表示额外空间的组件。
If you are trying to do something else then you need to clarify your question.
如果您正在尝试做其他事情,那么您需要澄清您的问题。
#2
You must have distinct instances for each buttonBlankItems
button. I guess that you are adding the same button 5 times and then you are trying to remove them.
您必须为每个buttonBlankItems按钮设置不同的实例。我猜你要添加相同的按钮5次,然后你试图删除它们。