Java - 关闭JFrame窗口时的消息

Mat*_*hew 5 java swing window jframe

我有一个Java程序,其中包含一个继承自JFrame 的类Application.

我想显示一条消息,询问用户是否要在单击窗口右上角的X按钮时退出程序.

到目前为止这是我的代码:

我从在线发现的教程中得到了这段代码.我自己编写了WindowClosing事件处理程序.但是,我在注册窗口侦听器(addWindowListener)时遇到问题.它告诉我WindowAdapter是抽象的,无法实例化.

我该如何解决这个问题?

Dan*_* D. 14

基本上,你几乎是正确的.有些事情没有正确拼凑而成.

首先删除你的WindowClosing方法(window不是Window),然后用addWindowListener(new WindowAdapter());下面的代码替换你

addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent e) {
    int confirmed = JOptionPane.showConfirmDialog(null, 
        "Are you sure you want to exit the program?", "Exit Program Message Box",
        JOptionPane.YES_NO_OPTION);

    if (confirmed == JOptionPane.YES_OPTION) {
      dispose();
    }
  }
});
Run Code Online (Sandbox Code Playgroud)