File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes LayoutManagers and containers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "LayoutManagers and containers " Watch "LayoutManagers and containers " New topic

LayoutManagers and containers

Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 528

Hi people,

I'm kind of new when it comes to designing a GUI. I find it REAL hard to actually place components where i'd like them. Is the use of LayoutManagers and various containers common in normal Swing GUI?

For example, would i divide the JFrame up into four containers (JPanels):
|_||_| (one JFrame, 4 JPanels)

and then each panel can get a diferrent LayoutManager implementation?

Would this be normal? (I can only use the Java Swing API and no other 3rd party project because it's for my SCJD).

And what i don't understand is why the components fill up all of the cells.

Can someone please help me with this design problem i am having?

Thanks and regards,


Live life to an interface, not an implementation!
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Is it normal to use LayoutManagers and Containers? Yes, of course. The only alternative is to use a "null" LayoutManager and place components at absolute coordinates. That's a terrible idea because just resizing a window breaks it, not to mention how it will break as the GUI is run on different platforms.

How to divide a window into 4 panels with their own LayoutManager? Easy. Set the LayoutManager of the JFrame's content pane to a GridLayout or GridbagLayout, and add four JPanels to that grid. GridLayout is simpler, but GridBagLayout would let the four panel's size vary.

Then you can independently set the LayoutManager of each of the JPanels; they can all be different.

Why do your components "take up the whole panel?" Well, each LayoutManager has its own strategy for laying out components; some of these strategies do, indeed, involve expanding components to fill available space. You need to read the Javadoc for each LayoutManager you use, carefully. JFrames have a BorderLayout by default; JPanels have a FlowLayout by default.

Have a look at the often-neglected Box class and the BoxLayout, which is a sort of improved FlowLayout.

[Jess in Action][AskingGoodQuestions]
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 528

Thanks Ernest.
I agree. Here's the link:
subject: LayoutManagers and containers
It's not a secret anymore!