javaswinglayoutjdialogpreferredsize

Swing: set a fixed window size for JDialog


I tried setPrefferedSize and setSize methods, but the dialog still opens at minimum size.

private void method() {
    commandDialog.setPreferredSize(new Dimension(100,100));
    - - - 
    - - -   //Components added to dialogPanel

    commandDialog.add(dialogPanel);

    // Tried this as well: commandDialog.setSize(40, 40);     
    commandDialog.validate();
    commandDialog.setVisible(true);
}

Solution

  • Don't forget to call pack() on the dialog before setVisible(true).

    Also, many here will recommend that rather than setting the dialog's preferredSize, overriding it or its content pane's getPreferredSize() method as a cleaner and safer way of having it size itself correctly.


    Edit
    Holger posted:

    Overriding getPreferredSize() is not better if it is just used to return the same constant size.

    I think that we all agree that having getPreferredSize() return a dumb constant size is usually to be avoided (although it is stable). Most of the time I avoid setting size/preferredSize or overriding getPreferredSize, but rather try to have my components and their own preferred sizes as well as the layout managers all size themselves, which again is initiated by the pack() method. Occasionally I will need to take a more active roll in trying to set the size of a component such as if I need to size a component to a background image, and then I'll override getPreferredSize() and use the image dimensions for the dimension returned, or will use some type of program logic to help figure out the best size. But again we all can agree that the less you futz with this, the better.


    Edit 2
    Holger posted:

    ... but the question is about a JDialog and dialogs never adapt themselves to their preferred size automatically.

    Again, they and all top-level windows do when you call pack() on them. Which was why I recommend this, and why this was my primary answer to his question.