开发者

Java Swing: Choosing the correct LayoutManager

开发者 https://www.devze.com 2023-03-15 11:47 出处:网络
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 automaticall

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 开发者_Go百科as well. Here is a screenshot:

Java Swing: Choosing the correct LayoutManager

    < 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):

Java Swing: Choosing the correct LayoutManager

    < GOOD

Thanks


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

Example layout:

Java Swing: Choosing the correct LayoutManager

Remember that you also can nest layouts.


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


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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消