【问题标题】:how to close only one awt Frame without closing other?如何只关闭一个awt Frame而不关闭另一个?
【发布时间】:2016-04-27 12:34:08
【问题描述】:

当我点击一帧的关闭(X)按钮时,它会关闭所有打开的帧。

我使用以下代码来关闭框架

    Frame f2 = new Frame();
        f2.setVisible(true);
        f2.setLayout(null);
        f2.setSize(500,500);
        f2.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent w)
            {
            System.exit(0);
            }       
        });

System.exit(0) 关闭整个应用程序。

我怎样才能只关闭一个框架??

【问题讨论】:

  • 1) 见The Use of Multiple JFrames, Good/Bad Practice? 2) 为什么使用 AWT?请参阅this answer 了解放弃 AWT 使用支持 Swing 的组件的许多充分理由。
  • 3) f2.setLayout(null); Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。

标签: java awt


【解决方案1】:

System.exit(); 导致 Java VM 完全终止。

所以你需要使用JFrame.dispose();,它会导致JFrame窗口被操作系统销毁和清理。

Frame f2 = new Frame();
    f2.setVisible(true);
    f2.setLayout(null);
    f2.setSize(500,500);
    f2.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent w)
        {
        f2.dispose();
        }       
    });

来自post的解释

【讨论】:

    【解决方案2】:

    你也可以使用dispose():

    import java.awt.Frame;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    public class Work {
    
        public static void main(String[] args) {
            Frame f2 = new Frame();
            f2.setVisible(true);
            f2.setLayout(null);
            f2.setSize(500, 500);
            f2.
            f2.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent w) {
                    w.getWindow().dispose();
                }
            });
        }
    }
    

    查看更多here。

    【讨论】:

      猜你喜欢
      • 2010-12-29
      • 2023-03-30
      • 1970-01-01
      • 2016-02-15
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      相关资源
      最近更新 更多