views:

53

answers:

2

I am failing to display a JComponent inside a JPanel on a JFrame.

The following does not work.

JComponent component = ...
panel.add(component, BorderLayout.CENTER);
frame.add(panel, BorderLayout.CENTER);

But if I add the JComponent to the JFrame[like frame.add(component, BorderLayout.CENTER);], it displays the contents.

Any ideas

+2  A: 

A JPanel's default layout is a FlowLayout so you don't have to specify the center of the panel.

Simply do:

panel.add(component);

Alternately, do:

panel.setLayout(new BorderLayout());
panel.add(component, BorderLayout.CENTER);
jjnguy
Thanks Justin. That is what I have done. My problem comes in when I do try to add the panel to the JFrame like this:frame.add(panel, BorderLayout.CENTER);. It does not display the component.
walters
Yes, Justin. That worked. Thanks.
walters
@wal, so your first comment is not valid then?
jjnguy
That is right Justin. Thanks.
walters
@Wal, ok. Glad I could help ya out.
jjnguy
+1  A: 

By default a JComponent doesn't have a preferred size.

By default a JPanel uses a FlowLayout. When you add a component to the panel it will respect the preferred size of the component, which is 0, so you don't see it.

By default the panel which is used as the content pane of a JFrame uses a BorderLayout. So when you add a component to the content pane of the frame the component is automatically resized to fill the space available to the frame,

The solution is to give your component a preferred size, then it can be used on any panel with any layout manager.

camickr