views:

46

answers:

2

When I am using the wait() method in the following code its throwing the following Exeption

Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException

The code is as follows:

private void newMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                            
        newFileChooser = new JFileChooser();

        int returnVal = newFileChooser.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            filename = newFileChooser.getSelectedFile();
            JFrame mainFrame = NetSimApp.getApplication().getMainFrame();
            networktype = new NetType(mainFrame);
            networktype.setLocationRelativeTo(mainFrame);
            NetSimApp.getApplication().show(networktype);
            try {
                this.wait();
            } catch (InterruptedException ex) {
               Logger.getLogger(NetSimView.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (!NetType.validip) {
                statusTextArea.append("File not created:Select Network Type.\n");
            }
            newNodeMenuItem.setEnabled(true);
        } else {
             newNodeMenuItem.setEnabled(false);
            statusTextArea.append("File not created:Access cancelled by user.\n");
        }
    }

Actually I am calling the object of a jDialog class and i want that the dialog object should complete first and then it should notify the above given code. I've already specified notify() in that class. Can anyone tell me whats the problem and its solution. -Thanks in advance

+2  A: 

Your wait method needs to be enclosed in a synchronized method or a lock block, with the object being locked on the object you want to wait upon.

In your case, you should make the method synchronized, which is equivalent to calling lock (this).

nasufara
+1  A: 

You have to start wait by acquiring synchronization on the wait variable, e.g.

synchronized( this )
{
    this.wait( );
}

Please read the javadoc for wait carefully and follow it to the letter, otherwise you'll be up to nasty surprises.

Alexander Pogrebnyak
for notfy() also I have to do the same thing??
Harshit Agarwal
@Harshit. Did you read javadoc?
Alexander Pogrebnyak