Returning value from JDialog; dispose(), setVisible(false) - example

16,527

Solution 1

Quoted from the Javadocs:

The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).

So, your Response will be kept. All dispose() does is releasing the native screen resources, other members aren't marked for garbage collection.

Also, if you want to be extra sure, you could just call dispose() right after you retrieved your response object.

Solution 2

if I close the dialog using dispose(), all dialog's resources can be garbage collected (don't have to... hard to predict, am I right?). So is it correct to retrieve my dialog's response it that way... Maybe in this case I should write only setVisible(false); without dispose().

Share:
16,527
radekEm
Author by

radekEm

Updated on June 22, 2022

Comments

  • radekEm
    radekEm almost 2 years

    I know, that this question appears quite frequently in SO like here: but I would like to present some very specific example... I'm simply not sure if I make things right.

    I've got a JDialog in which I can type some values, select some checkboxes... whatever... I've got also some Response object created in MyDialog which represents the MyDialog's "answer".

    In JFrame which calls/creates JDialog:

    MyDialog d = new MyDialog(this, ...);
    d.showDialog();
    // After MyDialog is closed (it's modal):
    MyDialog.Response dialogResponse = d.getDialogResponse();
    // Do something with response...
    

    In Dialog (dialog can be closed by clicking "Save" button):

    btnSave.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            dialogResponse = prepareResponse(); // prepares response on the basis of some data introduced by a user; dialogResponse is called from JFrame after Dialog is closed
            setVisible(false);
            dispose();  // <-- Important
        }
    });
    

    My question is: This solution works, I mean, the line MyDialog.Response dialogResponse = d.getDialogResponse(); returns proper values, but... if I close the dialog using dispose(), all dialog's resources can be garbage collected (don't have to... hard to predict, am I right?). So is it correct to retrieve my dialog's response it that way... Maybe in this case I should write only setVisible(false); without dispose().

  • GoAntonio
    GoAntonio about 10 years
    ??? clearly i missed a part here ....come on class variables are good they are necesary thats why we have them, factory methods constants like jdialogs butons you should read more