Displaying a JComponent inside a JPanel on a JFrame

walters picture walters · Aug 25, 2010 · Viewed 10k times · Source

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

Answer

jjnguy picture jjnguy · Aug 25, 2010

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