简体   繁体   English

如何使带有匿名内部类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();
            }
        });

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. 背景是variabel,所以我无法制作它,因此它和它具有相同的颜色,并假装它不存在。 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 : 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! EDIT2 :我认为由于计时器的缘故,我经常添加按钮时犯了一个很大的错误,感谢所有帮助,这仍然非常有用!

EDIT3 : Thank you all very much, I have fixed the problem with your guys' help :) EDIT3 :非常感谢大家,我已经在你们的帮助下解决了问题:)

If you want to remove the button: 如果要删除按钮:

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

If you don't need it after you 'dispose' of it, feel free to remove it from the parent. 如果您在“处置”之后不需要它,请随时将其从父项中删除。

button.getParent().remove(button);

Else, follow HoverCraftFullOfEel's advice. 否则,请遵循HoverCraftFullOfEel的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM