如何使用循环删除Java JButton?
我正在用java构建一个程序,我想知道是否有任何函数可以在按下on时删除JButton列表 这就是我到目前为止所做的:如何使用循环删除Java JButton?,java,swing,jbutton,actionlistener,Java,Swing,Jbutton,Actionlistener,我正在用java构建一个程序,我想知道是否有任何函数可以在按下on时删除JButton列表 这就是我到目前为止所做的: public void actionPerformed(ActionEvent e) { if(e.getSource() == button[0]) { for(int x = 0; x < 19; x++) { button[x].remove(this); } } } ActionListe
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button[0]) {
for(int x = 0; x < 19; x++) {
button[x].remove(this);
}
}
}
ActionListener已经配置好,可以正常工作。提前感谢您给了我一个解决方案。您当前的代码似乎试图从JButton(即bassackwards)中删除一些东西,您的this,无论它代表什么 关键信息是-从何处移除按钮?如果是一个JPanel,那么你必须这样做,调用remove。。。在包含的JPanel上,向组件传递要删除的JButton i、 e 具体的代码解决方案将取决于当前程序的结构。尝试以下方法:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button[0]) {
for(int x = 0; x < 19; x++) {
button[x].getParent().remove(button[x]);
}
}
}
在框架上添加按钮,并将动作列表设置为b[0]按钮
image 2) public void actionPerformed(ActionEvent e) {
if(e.getSource() == b[0]) {
for(int 1 = 0; 1 < 5; 1++) {
remove(b[x]);
}
}
}
1第一个图像添加框上的按钮
2第二个图像移除框架上的按钮
我认为您需要Containerremove,例如removebutton[x]甚至button[x]。getParent.removebutton[x],其中父项未知。。。
image 1) JButton b[]=new JButton[10];
for(int i=0;i<10;i++)
{
b[i]=new JButton(""+i);
b[i].setBounds(i*10,i*20,20,20);
add(b[i]);
}
b[0].addActionListener(this);
image 2) public void actionPerformed(ActionEvent e) {
if(e.getSource() == b[0]) {
for(int 1 = 0; 1 < 5; 1++) {
remove(b[x]);
}
}
}