简体   繁体   中英

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**
        }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM