Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new WindowListener to a JFrame

    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) {}

    });

There is my code, is it possible since I only use the windowClosing method to remove all the other in my case, useless methods so it takes less space?

Example

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

    });

Is it possible?

like image 896
Jonathan Beaudoin Avatar asked Nov 03 '12 08:11

Jonathan Beaudoin


People also ask

How to add a WindowListener in Java?

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.

Why do we implement WindowListener interface in frame window?

If a class needs to process some Window events, an object should exist which can implement the interface. As the object is already registered with Listener, an event will be generated on all the states of window. This helps in generation of invocation of relevant method in listener's object.

What is the use of WindowListener?

Window listeners are commonly used to implement custom window-closing behavior. For example, a window listener is used to save data before closing the window, or to exit the program when the last window closes.

What frame object method is used to register a Windows listener?

The object of that class must be registered with a component. The object can be registered using the addWindowListener() method.


1 Answers

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

like image 180
MadProgrammer Avatar answered Sep 19 '22 10:09

MadProgrammer