Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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().

image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...