开发者

Swing: easiest way to align width of [dynamic][static][dynamic] components?

What is the easiest way in standard Java Swing to align three components in such a way that:

  • the dynamic widths of Component1 and Component3 are adjusted to be equal,

  • while Component2 (which is in between) has constant width?

Imagine we have some resizable开发者_JAVA百科 JPanel (such as inside a JFrame).

Small width should look like this:

[----------------whole JPanel----------------]
[--Component1--] [Component2] [--Component3--]

Big width should look like this:

[------------------------whole JPanel------------------------]
[------Component1------] [Component2] [------Component3------]

Note: I just "trialed-and-errored" with GroupLayout for too long.


One option is using a GridBagLayout. A quick and dirty snippet to get you started:

GridBagConstraints gbc;
final int A_CENTER = GridBagConstraints.CENTER;  // anchor: center
final int F_NONE = GridBagConstraints.NONE;  // fill: none
final int F_DX = GridBagConstraints.HORIZONTAL;  // fill: dx only
final Insets IN_0 = new Insets(0, 0, 0, 0);  // empty insets

setLayout(new GridBagLayout() );
gbc = new GridBagConstraints(0, 0, 1, 1, 50.0, 0.0, A_CENTER, F_DX, IN_0, 0, 0);
add(new JButton("test1"), gbc);
gbc = new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, A_CENTER, F_NONE, IN_0, 0, 0);
add(new JButton("test2"), gbc);
gbc = new GridBagConstraints(2, 0, 1, 1, 50.0, 0.0, A_CENTER, F_DX, IN_0, 0, 0);
add(new JButton("test1"), gbc);

Obviously there's a lot more you can do with a GridBag, and you'll need to do some polishing to get exactly what you want to see, but this should get you started.

The fifth parameter in the GBC constructor is a weight for stretching in the x direction. Setting them equal, and forcing the center component not to stretch (F_NONE) does the dirty work.


How about the MigLayout manager? It is not a part of JRE, but is a great layout manager, which can easily produce the layout you require with less code than GridBag. Check out their demo.

Could not resist to post the totally grid bag cartoon... enjoy (:

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜