Reputation: 1467
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
Upvotes: 3
Views: 10835
Reputation: 324108
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.
Upvotes: 2
Reputation: 138874
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);
Upvotes: 5