Skip to content
Advertisement

JPanel takes the entire space of JFrame

I am struggling to place some simple objects using the FlowLayout manager in Swing.

Basically I have created a small program, I have set up the size of the frame, then crated some JLabels and then one JPanel.

I have put the JPanel a setSize of 300×300 and changed it’s color to red to visually see it. However it takes up the entire space of the JFrame and it seems that the setsize has no effect on it.

What am I doing wrong? I tried googling it and changed the code several time, but no luck. I even read, but clearly not understood correctly, the code on oracle… Please help. Underneath is my code so far.

JavaScript

Advertisement

Answer

JFrame uses BorderLayout as default LayoutManager. So you need to implicitly set layout of your JFrame to FlowLayout:

JavaScript

You also need to use setPreferredSize() instead of setSize() on your panel, because setSize() has no effect if container of your panel (JFrame) has non-null LayoutManager.

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