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 Laying out components in JPanel(s) and LayoutManager(s) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Laying out components in JPanel(s) and LayoutManager(s)" Watch "Laying out components in JPanel(s) and LayoutManager(s)" New topic

Laying out components in JPanel(s) and LayoutManager(s)

Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 519

Hi all,

I'm practicing Swing examples with JPanels and LayoutManagers to display the typical windows form. I'm not using any open source class because it's for my SCJD.

Picture this, i have a JFrame with a GridLayout manager of 3 by 3. Each cell contains a JPanel with a GridLayout manager for them also (actually not all of them). When i add components to the cells of the JPanels, they seem to be too far apart and all in the center of the cell, and because some components are bigger in height than other, they seem reall un-aligned and not very professional like. I'm sure there is something to align them in there corresponging cells, but what?, and is what i am doing normal?

Thanks in advance and best regards,


Live life to an interface, not an implementation!
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
It sounds like BoxLayout might be a little more appropriate for your purposes. Each cell in a GridLayout is exactly the same size and the cell size is made as large as possible given the available space and number of rows and columns. Thus if you have a GridLayout with two cells each cell will always occupy half the available space regardless of the size of the component in that cell. It sounds like your components are not resizeable so they end up floating off in the center of their cell. I would check the X and Y alignments of your components as that's most likely what GridLayout uses to align components smaller than their cell size. I don't see it specified in the API or in the Java Tutorial so you may have to fool around.

If you don't need each component to be in a cell of exactly the same size then I'd suggest rethinking what LayoutManager you're using. Check BoxLayout and GridBagLayout for starters.
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 519

Thanks for the reply Ken.
Daniel Dalton
Ranch Hand

Joined: Mar 20, 2005
Posts: 146
Or check SpringLayout - it can give some very nice and cantrollable results.
I agree. Here's the link:
subject: Laying out components in JPanel(s) and LayoutManager(s)
Similar Threads
Regarding layouts
Looking for layout advice
GUI from eclipse/WindowsBuilder not WYSIWYG
Adding padding to GUI components
Does FlowLayout honor the preferred size of a JPanel?