【问题标题】:add elements to a panel on the runtime in java [duplicate]在java中的运行时将元素添加到面板[重复]
【发布时间】:2013-01-10 22:49:28
【问题描述】:

可能重复:
How to dynamically add JLabels to JPanel?

我创建了一个面板并为其使用了网格布局。

public pnlFriends() {
    initComponents();
    this.setLayout(new GridLayout(10,1));
   // showFriends();

}

private void formComponentShown(java.awt.event.ComponentEvent evt) {
    showFriends();
    System.out.print("comp");
}

   private void showFriends()
   {
    //Integer id = NewMain.network.getEdges().get(Main.uuid).getDegree();
    for(int i = 0;i < 10 ;i++)
    {

        String name = "as";
        String occupation ="adf";
        String place = "asdf";
        Integer connections = 5;
        this.add(displayMiniProfile(name,occupation,place,connections));
    }
}

displayMiniProfile 返回一个 JPanel。

现在,当我在父 JPanel 的构造函数中调用此函数时,它可以工作,我可以添加 MiniProfile JPanel。

但是当我在 componentshown 事件的响应中调用这个函数时,它什么也没显示。

为什么?

我怎样才能达到同样的效果?

【问题讨论】:

  • 你没有向天空中伟大的编码之神祈祷吗?...没有SSCCE,一切都将是猜测工作...

标签: java swing layout constructor jpanel


【解决方案1】:

没有显示任何内容,因为在添加新面板后,JPanel 仍未得到验证。您需要致电

revalidate();
repaint();

调用后

this.add(displayMiniProfile(name,occupation,place,connections));

【讨论】:

  • 成功了。只是想再问一件事。会重新粉刷吗?
  • 不,这里需要revalidaterepaint 不会为新添加的面板进行必要的验证:)
  • @Reimeus 实际上是 revalidate()repaint() 来反映变化,在某些情况下只调用 revalidate 不会工作。
  • 在这种情况下,repaint() 并非绝对需要,但已将其添加为任何未来读者的“最佳实践”。
猜你喜欢
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
相关资源
最近更新 更多