Jaskaranbir Singh
Jaskaranbir Singh

Reputation: 2034

Start application as Dialog that calls parent frame

The situation is as follows:

My app consists of a dialog box containing x elements and a button. The user presses button after interacting with elements and if he interacted them with a specific way, only then the parent frame in which the Dialog Box resides should appear.

For this purpose, I currently know of this approach:

public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(false);
                jDialog.setVisible(true);
            }
        });
    }

And then add this command on Button which resides inside jDialog:

new NewJFrame().setVisible(true);

This does the trick quite well and neat, but the previous instance called using new NewJFrame().setVisible(false); is still running (as far as I know).

Isn't there anyway I could perform this action on button (residing inside jDialog) press as using something like:

NewJFrame.setVisible(true);

(It currently gives me error: Non-static method cannot be referenced from static context)

Upvotes: 1

Views: 224

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Make sure that the dialog is modal, and you can simply do:

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            NewJFrame newJFrame = new NewJFrame();
            newJFrame.pack();
            // no need to set visible false. It already is

            MyDialog myDialog = new MyDialog(newJFrame); 
            // make sure the super constructor makes the dialog modal

            myDialog.pack();
            myDialog.setVisible(true);

            // here the dialog is no longer visible
            // and we can extract data from it and send it to the JFrame if needed

            newJFrame.setVisible(true); // ****** here
        }
    });
}

Otherwise if you absolutely must fiddle with the JFrame from within the JDialog, simply pass the NewJFrame into the JDialog's constructor, something that you need to do regardless since it should be used in the JDialog super constructor, use it to set a NewJFrame field, and call setVisible(true) on the instance inside of your dialog.

Upvotes: 2

Related Questions