Display a confirmation when trying to close a JInternalFrame

1

I am creating a program using JInternalFrame , but I would like to request a confirmation if the user clicks the close button "Closable".

For this, I'm trying to overwrite the internalFrameClosed and internalFrameClosing methods, but I'm still not sure how to proceed, I tried to put setClosable(false) but it did not work.

    
asked by anonymous 26.12.2017 / 15:35

1 answer

1

You need to add a InternalFrameListener to the inner frame and override the internalFrameClosing() ", since it is called when trying to close JInternalFrame .

But since this type of internal window has, by default, the behavior of being hidden when closing it, it is not enough to implement something in this method, you have to tell the window to do nothing when closed, thus leaving all control in the superscript method. To do this, simply set the closing pattern:

seuFrameInterno.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);

And then add the listener:

seuFrameInterno.addInternalFrameListener(new InternalFrameAdapter() {

    @Override
    public void internalFrameClosing(InternalFrameEvent e) {

        int op = JOptionPane.showInternalConfirmDialog(getInstance(), "Quer mesmo fechar essa janela?", "Fechar Janela",
                JOptionPane.YES_NO_OPTION);

        if (op == JOptionPane.YES_OPTION) {
            dispose();
        }
    }
});

Notice that I'm using showInternalConfirmDialog() because since it's about internal frames, it does not make sense to display a JOptionPane window at the main screen level, but only within JDesktopPane . And it is mandatory to pass the internal frame instance as the first parameter. You can do this by creating a getInstance() method that returns the class instance itself, as I did:

private Component getInstance() {
    return this;
}

See working:

    
26.12.2017 / 17:34