Displaying a JComponent inside a JPanel on a JFrame

10,230

Solution 1

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

Solution 2

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.

Share:
10,230
walters
Author by

walters

Software Developer Follow me on twitter.

Updated on August 02, 2022

Comments

  • walters
    walters almost 2 years

    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