动态向JPanel添加组件 [英] Dynamically adding components to JPanel

查看:127
本文介绍了动态向JPanel添加组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将某些组件动态添加到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.

更新版本(添加一个新的JPanel,所有组件都将存在于其中):

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.

推荐答案

调用嵌套布局中所示,在父容器上为%28%29"rel =" nofollow noreferrer> validate() 例子.左下方的那些标签是动态添加的.请注意,调用pack()可能会导致GUI的大小发生变化,而调用validate()不会.如果需要以调整GUI的大小,请调用pack(),否则调用validate().

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

这篇关于动态向JPanel添加组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆