简体   繁体   中英

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. 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!

EDIT3 : Thank you all very much, I have fixed the problem with your guys' help :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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