Rob
Rob

Reputation: 762

Java Simple Question about working with JPanels

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)

Upvotes: 2

Views: 240

Answers (3)

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

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.

Upvotes: 3

John
John

Reputation: 6805

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.

Upvotes: 2

camickr
camickr

Reputation: 324207

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.

Upvotes: 3

Related Questions