Search code examples
javaswingjdialog

Swing JDialog bug?


I'm trying to create my own dialog by extending the JDialog class this is the code i used to start:

import javax.swing.JDialog;

public class ColorManager extends JDialog {
    private static final long serialVersionUID = 1L;

    public ColorManager(){
        super();
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        this.pack();
        this.setVisible(true);
    }
}

when i try to run the code it works fine but i'm getting the following exception:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, or DISPOSE_ON_CLOSE

i read that there were problems with WINDOWS_EXIT or something like that but the parameter i pass should do the job. the thing that makes it even weirder is that when i change my class so it will contain a JDialog field instead of extending it, it seems to work just fine. I asked a friend to test this on his computer and the code did not throw the exception, he is using jre version 1.6.022 and I'm using 1.6.022 both of us are using 64 bit.

so what did i do wrong? or is that a bug in the JRE?

Edit: forgot to mention, I'm using eclipse
Edit2: i tried the same code in Netbeans and it works fine, what could be my problem??


Solution

  • All the methods you call in constructor should be called on the EDT thread. It is not advised to do it inside the constructor, but if you insist make sure it runs on Swing (EDT) thread such as:

    import javax.swing.JDialog;
    
    public class ColorManager extends JDialog {
        private static final long serialVersionUID = 1L;
    
        public ColorManager(){
            super();
             SwingUtilities.invokeLater(new Runnable() {
                 public void run() {
                    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                    this.pack();
                    this.setVisible(true);
                 }
             });
        }
    }
    

    IMO the best way do accomplish it would be to move this into separate method and then call it after creating your ColorManager instance.

    When using Swing you should always adhere to Swing threading rules. More information can be found at

    http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html