如何使带有匿名内部类actionlistener的JButton在单击时自行删除? [英] How do I make a JButton with an anonymous innerclass actionlistener remove itself on click?
问题描述
您好,感谢您提前阅读本文,这是我的问题:
Hello and thanks for reading this in advance, here is my problem:
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionevent)
{
button.setVisible(false);
button.validate();
button.invalidate();
button.revalidate();
button.repaint();
}
});
我尝试了所有这些操作,只是使该按钮消失了,我也禁用了它,但是我需要它只是消失,而不是消失或什么。背景是variabel,所以我无法制作它,因此它与它的颜色相同,并假装它不存在。有没有人知道如何使它消失?
I have tried all those to just make that button go away, I have disabled it aswell, but I need it to just go away, not fade out or something. the background is variabel so I can't make it so it has the same color as it and pretend it's not there. Does anyone have any clue at all how to make it go away?
编辑:我已经尝试了所有答案,真的很想谢谢你,但是按钮仍然存在:(
EDIT: I've tried all answers uptill now and would really like to thank you, but the button's still there :(
EDIT2 :我认为由于不断添加按钮,我犯了一个很大的错误我的计时器,感谢所有帮助,这仍然非常有用!
EDIT2: I think I've made quite a big mistake constantly adding buttons because of my timer, thanks for all the help, this still was very usefull!
EDIT3 :非常感谢,我已经解决了问题在你们的帮助下:)
EDIT3: Thank you all very much, I have fixed the problem with your guys' help :)
推荐答案
如果要删除按钮:
Container parent = button.getParent();
parent.remove(button);
((JComponent) parent).revalidate();
parent.repaint();
如果要从按钮中删除动作监听器,则:
if you want to remove action listener from the button:
public void actionPerformed(ActionEvent actionevent)
{
button.removeActionListener(this);
}
这篇关于如何使带有匿名内部类actionlistener的JButton在单击时自行删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!