简体   繁体   中英

Displaying a JComponent inside a JPanel on a JFrame

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM