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 Regarding layouts Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Regarding layouts" Watch "Regarding layouts" New topic

Regarding layouts

Vivek Chaitanya
Ranch Hand

Joined: Oct 19, 2007
Posts: 35
Hi There

I want to construct a Swing GUI where I want to place labels and controls in a 4X2 matrix. I want to give sufficient spaces in between so that the GUI looks great.

I wanted to have only one Label and its corresponding control like JTextBox etc in a single line, for the next Label and control I should move to next line.

I am sure it is very common problem.

Is there any standard solution for that?

Rob Spoor

Joined: Oct 27, 2005
Posts: 20271

Ifm you want to torture yourself ( ;) ) you could look at the GridBagLayout and its partner in crime GridBagConstraints. They're quite a pain to work with.

If all labels and text fields can be equally large you can use a GridLayout. This layout, which can take a parameter in the constructor for the gap, can display all components in a sort of table. Each of the cells of the table is equally large, and filling the complete size of the parent container. So if your panel resizes, all these cells resize as well. I wouldn't recommend this layout if your panel can resize.

My favourite layout manager is the FormLayout from Like the GridLayout it creates a table inside your panel, but you can specify a lot better for each row and column what the size should be. GridBagLayout can do the same but is much more complex.
An example:

Some comments: each column specification is separated by a comma. pref means that the preferred size of the largest component is used. All other components are resized. fill:pref:g means pref, but if the panel resizes this control resizes along. The 1dlu is the default spacing in FormLayout GUIs; you can omit it (meaning no gaps between the controls) or increase it.

Unlike arrays, cells numbering starts at 1. For the rest it's quite similar to arrays. You can also specify that a component should stretch over multiple cells; use cc.xywh(1, 1, 3, 1) to stretch over the first three columns of the first row.

Java 1.6 introduced the GroupLayout which may also do what you want, but I haven't used it yet.

[ November 02, 2007: Message edited by: Rob Prime ]
[ November 02, 2007: Message edited by: Rob Prime ]

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Regarding layouts
It's not a secret anymore!