首页 文章

Java - 关闭JFrame窗口时的消息

提问于
浏览
5

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

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

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

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

我该如何解决这个问题?

3 回答

  • 0

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

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

    我在两分钟内得到了这个......

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

    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);
        }
    }
    });
    }
    
  • 2

    好的再试一次 .

    您无法创建新的WindowAdapter,因为WindowAdapter是抽象的 . 抽象类无法实例化 . 您需要创建WindowAdapter的子类并将其抽象方法实现为public .

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

相关问题