Gruxer
Gruxer

Reputation: 13

Java JFrame popup window

So I'm fairly new to Java Swing, and I stumbled upon a certain difficulty. I have a main Frame running (main part of the application that is visible throughout the app's execution) which has a button that once clicked, invokes a popup Frame (window) to collect user's information, and that frame has some Components. The problem being is that I don't really know the right approach to invoking the popup window and the main window freezing the execution and waiting until OK, or cancel button is clicked on the popup. Once this happens the main window code collects the returned values from the popup and resumes. I tried using synchronization to accomplish this, however the popup components don't even load, just the JFrame and JPanel (white background) and the popup freezes up on the wait() condition. I know that there is a way of doing it with JDialog and others, my main concern however, is to discover why the popup frame doesn't load the components and freezes up before the wait() condition. (when I get rid of wait() everything loads properly).

    //in Main window Class:
    frame.setEnabled(false);
    Test test = getNewTest(); //should freeze on wait() in popup window
    frame.setEnabled(true);

    //in Popup Window Class
    public Test getNewTest() {

    addPanel.setVisible(true);
    addFrame.setVisible(true);

    synchronized(flag) {
        try {
            flag.wait();
        } catch (InterruptedException e) {}
    }

    addPanel.setVisible(false);
    addFrame.setVisible(false);

    if(success)
    return new Test(testName, date);
    else return null;
}


    //When OK or Cancel button clicked appropriate handler sets
    //success value and invokes flag.notify();

Upvotes: 1

Views: 6995

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

  • Get all that synchronized and wait stuff out of your code. All that will do is freeze the Swing event thread, rendering your application useless.
  • You don't want to use a second JFrame, since an application typically has only one main window or JFrame, not multiple.
  • You want instead to use a modal dialog such as a JOptionPane (which can hold complex GUI's), or a modal JDialog (which also can hold a complex GUI). Be sure to associate the modal dialog with the parent JFrame. The Swing GUI library will then freeze the main window until the dialog has been dealt with, and the code from the main GUI will resume from the place the dialog was made visible after the dialog is no longer visible.

Upvotes: 2

Related Questions