venerdì 29 ottobre 2010

Netbeans - Prevent FrameView from closing

Preventing FrameView from quitting seems to be such a difficult operation. Browsing the internet and testing all of the suggestions, I found out a way to achieve what I want. Let's immagine that we want to build an application called MyProggy. Netbeans' ll create two files, respectively called MyProggyAPP.java and MyProggyView.java. MyProggyApp is the main class, MyProggyView takes care of creating the frame.
In MyProggyApp.java we can modify the startup void in this way (overriding CanExit() and WillExit methods):
    /**
     * At startup create and show the main frame of the 
     * application.
     */
    @Override protected void startup() {
        show(new MyProggyView(this));

        // Create the ExitListener
        ExitListener exitListener = new ExitListener() {    
            public boolean canExit(EventObject arg0) { 
                // return statement
                return false; 
            }

            public void willExit(EventObject arg0) {}
        };
        // Add the Listener
        addExitListener(exitListener);
    }
After that, in MyProggyView.java we can override the WindowClosing void (and WindowIconified, WindowDeiconified...)
    final JFrame frame = this.getFrame();

    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowIconified(WindowEvent evt) {
            // Do something
        }

        @Override        
        public void windowClosing(WindowEvent e) {
            // Do something
        }
     });

That's all, we're done.

Best regards.