1

Possible Duplicate:
How to dynamically add JLabels to JPanel?

I have a created a panel and using a gridlayout for it.

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

where the displayMiniProfile return a JPanel.

Now when I have this function called in the constructor of the parent JPanel, it works and I can add MiniProfile JPanel.

But when I am calling this function in the response of componentshown event it doesn't show anything.

WHY ?

And how can I achieve the same ?

Community
  • 1
  • 1
jairaj
  • 1,789
  • 5
  • 19
  • 32
  • 2
    You failed to pray to great coding gods in the sky?...Without an [SSCCE](http://sscce.org/) everything would be guess work... – MadProgrammer Jan 10 '13 at 23:10

1 Answers1

3

Nothing is shown because the JPanel still has not been validated after the new panel has been added. You will need to call

revalidate();
repaint();

after calling

this.add(displayMiniProfile(name,occupation,place,connections));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • it worked. Just wanted to ask one more thing.Will repaint work ? – jairaj Jan 10 '13 at 23:38
  • 1
    No, you need `revalidate` here, `repaint` won't do the validation necessary to account for the newly added panel :) – Reimeus Jan 10 '13 at 23:40
  • 1
    @Reimeus it would actually be `revalidate()` and `repaint()` to reflect the changes, calling only `revalidate` wont wok in some cases. – David Kroukamp Jan 11 '13 at 06:13
  • In this case, `repaint()` not strictly needed but have added it to answer as "best practice" for any future readers. – Reimeus Jan 11 '13 at 10:14