user1701840
user1701840

Reputation: 1112

how to add Jlabel to Jpanel outside the constructor?

I am able to use add(new Jlabel()) to create label on my Jpanel inside the Jpanel constructor, but once I called add() using other function, the label is not shown on the panel. What did I do wrong?

public class DisplayPanel extends JPanel {


        JLabel headerField = new JLabel("Choose a file to generate report.");

        JLabel dateField = new JLabel("123");
        JLabel meanField = new JLabel("");

        JLabel minField = new JLabel("");

        JLabel maxField = new JLabel("");

        JLabel stdDevField = new JLabel("");

        public DisplayPanel() {
        super();
                setBackground(Color.white);
                setLayout(new GridLayout(6, 1));


        add(headerField);
        **//add(new JLabel("123")); this will work**

        }


        public void setFields(DataManager d)
        {
            dateField.setText(d.getStartDate() + " - " + d.getEndDate());
            meanField.setText("Mean: " + d.getMean());
            minField.setText("Min: " + d.getMin());
            maxField.setText("Max: " + d.getMax());
            stdDevField.setText("Std Dev: " + d.getStdev());
            this.add(new JLabel("123")); **//this doesn't work**
        }

Upvotes: 1

Views: 1138

Answers (1)

Reimeus
Reimeus

Reputation: 159784

In order to get any newly added component to appear after the JPanel has been made visible, you need to call revalidate() and typically repaint(). The reason that

add(new JLabel("123"));

works in the constructor the JPanel is validated when added to its container, typically a JFrame. Adding the label at the inialization stage is simpler as you only have to call JLabel#setText and no revalidate/repaint calls are necessary.

Upvotes: 5

Related Questions