Martijn Courteaux
Martijn Courteaux

Reputation: 68907

Java Swing: Choosing the correct LayoutManager

I'm building a PropertyPanel. Currently I'm using a GridLayout to manage the JLabels and their corresponding fields where I can specify the value. But the problem is that the GridLayout automatically manages the size of the columns: it makes them the same width.

This means when I'm having a big value field, the colum, is getting bigger (which is good), but the other column (with all my JLabels) is getting bigger as well. Here is a screenshot:

enter image description here     < BAD

As you can see, the image property has a huge value, which makes both columns bigger, and I'm having a lot of space after the JLabels.

So, I'm searching for a LayoutManager which makes each column as big as necessary.
I want a layout like this (it's edited with Gimp):

enter image description here     < GOOD

Thanks

Upvotes: 5

Views: 3571

Answers (6)

Andrew Thompson
Andrew Thompson

Reputation: 168845

While this was answered 11 hours ago, I just thought I'd pop in & make a suggestion. I suggest GroupLayout.

I was looking to break from nested layouts for a name/value dialog recently and looked at both GroupLayout & SpringLayout. It seemed the only advantage offered by SpringLayout was that it could achieve the right aligned text of the labels (there may be a way to do it using GL, but I couldn't figure out how). On the downside, the Java Tutorial examples for SpringLayout used a whopping 'helper class' to define layout constraints.

In the end (it was only a very short 'study') I chose to use GroupLayout.

Upvotes: 2

Rocky Pulley
Rocky Pulley

Reputation: 23321

I tend to try to hack everything by mixing GridLayout and BorderLayout, so maybe it's not the best solution but...

Create two GridLayouts, both have a single column. One for the labels the other for the controls.

Now create a BorderLayout to be the parent.

Add the left grid to the BorderLayout.WEST and the right grid to the BorderLayout.CENTER.

Upvotes: 2

Puce
Puce

Reputation: 38152

Here's an overview of the standard LayoutManagers: http://download.oracle.com/javase/tutorial/uiswing/layout/visual.html

You could e.g. use GridBagLayout or the non-standard MigLayout, if you want to code the GUI by hand.

If you want to use a GUI builder (e.g. the one in NetBeans) you could use the GroupLayout.

Upvotes: 1

jzd
jzd

Reputation: 23639

SpringLayout is what I typically use for forms like this. Although I think GridBagLayout would also work nicely.

Upvotes: 2

Michael Brewer-Davis
Michael Brewer-Davis

Reputation: 14296

Consider using MigLayout. If constrained within the current JDK, GridBagLayout.

Upvotes: 1

Jonas
Jonas

Reputation: 129075

You can use SpringLayout for this. See How to Use SpringLayout.

Example layout:

enter image description here

Remember that you also can nest layouts.

Upvotes: 5

Related Questions