我试图动态地将一些组件添加到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
}
}
可惜的是没有什么改变。
你尝试调用'包()'父'JFrame'? – Jack 2012-04-10 17:21:21
还没有。仅仅调用revalidate()或其他的东西是不够的? – user1170330 2012-04-10 17:22:26
JPanel的布局是什么?一些组件可以在一些布局中重叠,如BorderLayou。尝试BoxLayout或FlowLayout。 – elias 2012-04-10 17:50:33