动态添加组件到JPanel

时间:2012-04-10 17:18:35

标签: java swing jpanel

我正在尝试动态地将一些组件添加到JPanel,但不幸的是它们没有出现。我只看到构造函数中添加的那些。

更新版本(添加新的JPanel,其中包含所有组件):

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

不幸的是没有改变。

1 个答案:

答案 0 :(得分:6)

在父容器上调用validate(),如Nested Layout Example所示。左下角的标签是动态添加的。请注意,调用pack()可能会导致GUI的大小发生变化,而调用validate()则不会。如果需要要让GUI调整大小 - 请致电pack(),否则请致电validate()