简体   繁体   English

动态添加组件到 JPanel

[英]Dynamically adding components to JPanel

I'm trying to dynamically add some components to a JPanel, but unfortunatelly they don't appear.我正在尝试将一些组件动态添加到 JPanel,但不幸的是它们没有出现。 I only see the ones added in the constuctor.我只看到构造函数中添加的那些。

Updated version (adding a new JPanel, where all the components will be):更新版本(添加一个新的 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
  }
}

Unfortunatelly nothing changed.不幸的是什么都没有改变。

Call validate() on the parent container, as shown in the Nested Layout Example .在父容器上调用validate() ,如嵌套布局示例中所示。 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.请注意,调用pack()可能会导致 GUI 的大小发生变化,而调用validate()则不会。 If you need to get the GUI to resize - call pack() , else call validate() .如果您需要调整 GUI 的大小 - 调用pack() ,否则调用validate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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