Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 209
Martijn Courteaux Avatar asked Jun 23 '11 16:06

Martijn Courteaux


People also ask

How do you decide which layout manager is to be selected for the GUI?

Tips on Choosing a Layout Manager Also keep in mind that flexible layout managers such as GridBagLayout and SpringLayout can fulfill many layout needs. Scenario: You need to display a component in as much space as it can get. If it's the only component in its container, use GridLayout or BorderLayout .

Which is the correct constructor of grid layout?

Constructors of GridLayout classGridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns along with given horizontal and vertical gaps.

How do I set preferred size in Java?

setSize will resize the component to the specified size. setPreferredSize sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.

Which is the default layout in swing?

The FlowLayout is the default layout. It layout the components in a directional flow. The GridLayout manages the components in the form of a rectangular grid. This is the most flexible layout manager class.


2 Answers

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

Example layout:

enter image description here

Remember that you also can nest layouts.

like image 71
Jonas Avatar answered Oct 10 '22 20:10

Jonas


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

like image 21
jzd Avatar answered Oct 10 '22 21:10

jzd