繁体   English   中英

如何从JButton的ActionListener中删除JFrame中的JButton?

[英]How to remove JButton from JFrame from inside JButton's ActionListener?

在编写我的Swing应用程序时,我总是遇到麻烦,我想我终于得到了一个明确的答案而不是玩它直到我开始工作......

我有一个JFrame。 在这个JFrame里面是一个JButton。 在ActionListener中,我想几乎清空JFrame,留下一个或两个组件(包括删除JButton)。 然后应用程序冻结,因为在ActionListener完成之前,您无法删除该组件。 我该如何解决这个问题?

当您删除组件时,不要忘记在容器上调用validate()repaint() ,并且应该正常工作。

import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class RemoveDemo {

    static class RemoveAction extends AbstractAction{
        private Container container;

        public RemoveAction(Container container){
            super("Remove me");
            this.container = container;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            container.remove((Component) e.getSource());
            container.validate();
            container.repaint();    
        }
    }

    private static void createAndShowGUI() {
        final JFrame frame = new JFrame("Demo");
        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        RemoveAction action = new RemoveAction(frame);
        frame.add(new JButton(action));
        frame.add(new JButton(action));

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

使用EventQueue.invokeLater()在事件队列中添加合适的Runnable 它“将在处理完所有待处理事件后发生”。

暂无
暂无

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

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