Search code examples
javaswingjlabeljdialogpack

JDialog.pack() hides JLabel


I am trying to write a form in java, but after dynamically inserting JLabels to the current JDialog and doing a pack() the windows is resized to minimum. The JLabels are displayed, but I have to resize the window manually. Here is the part where the JLabels are inserted:

public void displayQuizz(Test quiz){
        int xLable = 44;
        int yLable = 41;
        int widthLable = 403;
        int heightLable = 70;
        int noOfQuestion = 1;
        for(Question question : quiz.getQuestions()){
            JLabel lblNewLabel = new JLabel(Integer.toString(noOfQuestion) + ". " + question.getStatement());
            lblNewLabel.setBounds(xLable, yLable, widthLable, heightLable);
            contentPanel.add(lblNewLabel);
            contentPanel.revalidate();
            contentPanel.repaint();
            this.pack();

            noOfQuestion++;
            yLable += heightLable;
        }



    }

Solution

  • The pack() method sets the size of a Window (where JFrame and JDialog are subclasses from) to the preferred size.

    The preferred size is determined by

    • The LayoutManager, which takes the arrangement of the components and their preferred size into account
    • The component itself, if it does not have a layout manager

    As you don't use a layout manager in your example (and set the bounds of the label manually), you also have to specify the preferred size yourself (see getPreferredSize(), the default is 0x0, that's the problem you encountered).

    I'd encourage you to get used to always use layout managers (there's quite a lot of them, and you can easily write your own layout manager strategy if none suffices your needs).