将新的WindowListener添加到JFrame

Jon*_*oin 4 java swing jframe joptionpane windowlistener

    mainFrame.addWindowListener(new WindowListener() {

        @Override
        public void windowClosing(WindowEvent e) {
            if (JOptionPane.showConfirmDialog(mainFrame, "Are you sure you want to quit?", "Confirm exit.", JOptionPane.OK_OPTION, 0, new ImageIcon("")) != 0) {
                return;
            }
            System.exit(-1);
        }

        @Override 
        public void windowOpened(WindowEvent e) {}

        @Override 
        public void windowClosed(WindowEvent e) {}

        @Override 
        public void windowIconified(WindowEvent e) {}

        @Override 
        public void windowDeiconified(WindowEvent e) {}

        @Override 
        public void windowActivated(WindowEvent e) {}

        @Override 
        public void windowDeactivated(WindowEvent e) {}

    });
Run Code Online (Sandbox Code Playgroud)

有我的代码,是否可能,因为我只使用windowClosing方法删除我的情况下的所有其他方法,无用的方法,所以它占用更少的空间?

    mainFrame.addWindowListener(new WindowListener() {

        @Override
        public void windowClosing(WindowEvent e) {
            if (JOptionPane.showConfirmDialog(mainFrame, "Are you sure you want to quit?", "Confirm exit.", JOptionPane.OK_OPTION, 0, new ImageIcon("")) != 0) {
                return;
            }
            System.exit(-1);
        }

    });
Run Code Online (Sandbox Code Playgroud)

可能吗?

Mad*_*mer 10

There is a default implementation of WindowListener called WindowAdapter which allows you to override the methods you really want to use

  • 对于其他听众来说也是如此,例如`MouseListener` /`MouseAdapter`,`MouseMotionListener` /`MouseMotionAdapter`,`KeyListener` /`KeyAdapter`等. (3认同)