【问题标题】:Java - Message when closing JFrame WindowJava - 关闭 JFrame 窗口时的消息
【发布时间】:2012-11-05 09:02:18
【问题描述】:

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

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

这是我目前的代码:

我从网上找到的教程中获得了此代码。我自己编写了 WindowClosing 事件处理程序。但是,我无法注册窗口侦听器 (addWindowListener)。它告诉我 WindowAdapter 是抽象的,无法实例化。

请问我该如何解决这个问题?

【问题讨论】:

  • 您确定要解决这个问题吗? (TM) ;-)
  • 我当然想解决它;)

标签: java swing window jframe


【解决方案1】:

基本上,你得到的几乎是正确的。有一些东西没有正确组合和一个错字。

首先删除您的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();
    }
  }
});

【讨论】:

  • 非常感谢您的帮助 :) 您的解决方案完美运行 :)
  • @Matthew 如果您使用的是 Java 5(+),则可以使用 @Override 注释来表明您打算扩展超类中的方法,即 windowClosing。然后你会收到一个编译错误,因为你的错字。
  • @DuncanJones 谢谢你的建议 :)
【解决方案2】:

我在两分钟内完成了编码......

首先在Exit_on_close中设置j帧默认关闭事件。其次创建一个名为“Window Closing Event Handler”的类,然后在init阶段调用它。

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

    if (confirmed == JOptionPane.YES_OPTION) {
        try{
            String login=txtuserid.getText();
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/repair", "root", "");
            Statement st = conn.createStatement();
            String update = "UPDATE user set User_Status=0 where UserID='"+ login +"'";
            st.executeUpdate(update);  
            dispose();
            Login2 dialog = new Login2(new javax.swing.JFrame(), true);
            dialog.setVisible(true);
        }catch(SQLException | HeadlessException q){
            JOptionPane.showMessageDialog(null, q);
        }
        System.exit(0);
    }
    else{
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    }
}
});
}

【讨论】:

    【解决方案3】:

    好的,再试一次。

    您不能创建 新的 WindowAdapter,因为 WindowAdapter 是抽象的。抽象类不能被实例化。您需要创建 WindowAdapter 的子类并将其抽象方法实现为公共的。

    http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowAdapter.html

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多