简体   繁体   中英

Dynamically adding components to JPanel

I'm trying to dynamically add some components to a JPanel, but unfortunatelly they don't appear. I only see the ones added in the constuctor.

Updated version (adding a new JPanel, where all the components will be):

public class View extends JPanel {

JPanel panel = new JPanel();
JLabel label;
JLabel labels[];
JButton b1 = new JButton("OK");

public View() {
   this.setLayout(new FlowLayout());
   this.add(panel); // adding a new JPanel
   label = new JLabel("My label");
   panel.add(label);  // adding label to the new panel (this one works)
}


public void showLabels() {
  System.out.println("function showLabels called");

  labels = new JLabel[5];

  for (int i = 0; i < 5; i++) {
      labels[i] = new JLabel("Label: " + i);
      panel.add(labels[i]); // this one doesn't work
  }
  panel.add(b1); // this one doesn't work, too
    this.validate(); // validating this class (parent container)
    panel.validate(); // validating the panel, where all the components are
  }
}

Unfortunatelly nothing changed.

Call validate() on the parent container, as shown in the Nested Layout Example . Those labels on the lower left are added dynamically. Note that calling pack() might cause the size of the GUI to change, whereas calling validate() won't. If you need to get the GUI to resize - call pack() , else call validate() .

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