【问题标题】:Can't remove a JFrame's added components on mouseclick鼠标单击时无法删除 JFrame 添加的组件
【发布时间】:2022-10-06 23:12:16
【问题描述】:

我试图让一个按钮从 JFrame 中删除所有元素,以便我可以添加新元素。但是,当我单击按钮时,框架被冻结并且没有任何内容被删除。我创建了这个最小的例子:

public class Main {
    static JFrame frame;

    public static void main(String[] args){
        frame = new JFrame();
        frame.setSize(new Dimension(300, 300));

        JButton b = new JButton(\"Die\");
        b.addActionListener(e -> {

        });

        frame.add(b);
        frame.setVisible(true);

    }

    public void die(){
        frame.removeAll();
        frame.repaint();
    }
}

我做错了什么,我该如何解决?

    标签: java swing


    【解决方案1】:

    1.在按钮的单击操作中调用 die()

    public static void main(String[] args){
        frame = new JFrame();
        frame.setSize(new Dimension(300, 300));
    
        JButton b = new JButton("Die");
        b.addActionListener(e -> {
          die();
        });
    
        frame.add(b);
        frame.setVisible(true);
    }
    

    2.从框架的内容窗格中删除

      public void die(){
          frame.getContentPane().removeAll();
          frame.repaint();
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多