Skip to content
Advertisement

Putting panels in a big Panel

I want to create a Frame with a big panel with flow layout which contains several smaller panels with a given size. I thought I could do like this: (The JFrame is given)

JavaScript

If I run this, I just get my big panel in gray and I only see a small red square in the top middle of my frame, although I set the size to 300px and 200px.

Advertisement

Answer

The displayed size of a component is determined by the layout manager. Some layout managers use the value returned by method getSize but not any of the ones that you are using in your code.

As you correctly stated, the default layout manager for JPanel is FlowLayout and FlowLayout actually uses the value returned by method getPreferredSize. Hence, rather than calling method setSize, call setPreferredSize. Below code demonstrates. (More explanations after the code.)

JavaScript

The default layout manager for the [content pane of] JFrame is BorderLayout. In the code in your question, you are actually adding panel to the center of BorderLayout which means that it will take up all the available space.

Since you don’t set any size for panel its size will be determined by the size of its parent. Hence, in my code, above, I explicitly set the size of the JFrame. Otherwise, you would only see panel1. (I suggest that you modify the above code and see for yourself. Replace frame.setSize(450, 300); with frame.pack();)

This is how it looks when I run the above code.

screen capture

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement