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



我在编写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。它"将在处理完所有未决事件后发生。"

最新更新