views:

71

answers:

3

Just a quick question here. I have a program in which I need to create a number of JPanels, which will then each contain some objects (usually JLabels).

There are a few operations that I have to do each time i create a new JPanel, and I'm wondering if the order in which I do them has any bearing, or if there is a standard practice.

The operations I do are the following:

Declare the JPanel: JPanel panel = new JPanel(...)

Declare the JLabel: JLabel laberl = new JLabel...

Add the JPanel to some other content pane: frame.getContentPane().add(panel)

Set the bounds of the JPanel: panel.setBounds(...)

Add the JLabel to the JPanel: panel.add(label)

+3  A: 

In general order isn't important as long as you add all the components to the panel and the panel is added to the content pane "before" you make the frame visible.

The standard practice is to use a layout manager, so there would be no need to set the bounds of the panel you added to the content pane.

camickr
+2  A: 

Have a method createPanel() that returns the panel with all its children added.

Panel p = createPanel();
p.setBounds(...); // if you must
frame.getContentPane().add(p);

And then

Panel createPanel() {
  Panel p = new Panel();
  Label l = new Label("Heading");
  p.add(l);
  return p;
}

The order of constructing and adding items isn't important, except that when you add children, you should add them in the order you want them in the panel.

John
+3  A: 

The order doesn't matter. However, after creating and adding everything, you need to call revalidate() on the panel (or pack() on its parent window) so that the layout manager (I presume you're using one!) arranges the components as they should be.

Joonas Pulakka