• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:GroupLayoutの使用
#navi(../)
*GroupLayoutの使用 [#j81288d1]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2007-07-30~
更新日:&lastmod;

#contents

**概要 [#tfb59c68]
JDK 6 で新しく導入されたGroupLayoutとGridBagLayoutを比較しています。GroupLayoutのサンプルは、APIドキュメントの例をそのまま引用しています。

#screenshot

**サンプルコード [#aa18780d]
#code{{
//GroupLayout
JPanel p1 = new JPanel();
p1.setBorder(BorderFactory.createTitledBorder("GroupLayout"));
GroupLayout layout = new GroupLayout(p1);
p1.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);

GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();

hGroup.addGroup(layout.createParallelGroup()
    .addComponent(label1).addComponent(label2));
hGroup.addGroup(layout.createParallelGroup()
    .addComponent(tf1).addComponent(tf2));
layout.setHorizontalGroup(hGroup);

GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE)
    .addComponent(label1).addComponent(tf1));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE)
    .addComponent(label2).addComponent(tf2));
layout.setVerticalGroup(vGroup);
}}

#code{{
//GridBagLayout
JPanel p2 = new JPanel(new GridBagLayout());
Border inside  = BorderFactory.createEmptyBorder(10,5+2,10,10+2);
Border outside = BorderFactory.createTitledBorder("GridBagLayout");
p2.setBorder(BorderFactory.createCompoundBorder(outside, inside));
GridBagConstraints c = new GridBagConstraints();
c.gridheight = 1;

c.gridx   = 0;
c.insets  = new Insets(5, 5, 5, 0);
c.anchor  = GridBagConstraints.WEST;
c.gridy   = 0; p2.add(label3, c); //p2.add(new JLable("一度だけのaddで"), c);
c.gridy   = 1; p2.add(label4, c); //p2.add(new JLable("いいのは利点かも"), c);
c.gridy   = 0; p2.add(label3, c); //p2.add(new JLabel("一度だけのaddで"), c);
c.gridy   = 1; p2.add(label4, c); //p2.add(new JLabel("いいのは利点かも"), c);

c.gridx   = 1;
c.weightx = 1.0;
c.fill    = GridBagConstraints.HORIZONTAL;
c.gridy   = 0; p2.add(tf3, c);
c.gridy   = 1; p2.add(tf4, c);
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#f747ae82]
GroupLayoutを手で書く場合は、少ないかもしれませんが、それでもGridBagLayoutと同程度の記述で同じようなレイアウトも作成できるようです。また手書きでも、GroupLayoutの場合、コンテナとコンポーネントの間に、ギャップを自動的に作成してくれる GroupLayout#setAutoCreateContainerGapsなどが便利です((GridBagLayoutだと、コンテナにBorderを使用してギャップを作る))。

上記のサンプルでは、GroupLayout、GridBagLayoutでレイアウトしたパネルを、GridLayout((BorderLayout.CENTERと同じで、推奨サイズが無視される))で上下に並べているため、フレームを拡大すると、GroupLayoutは上揃え、GridBagLayoutは中央揃えになっています。

**参考リンク [#l70114e0]
-[[GroupLayout (Java Platform SE 6)>http://java.sun.com/javase/ja/6/docs/ja/api/javax/swing/GroupLayout.html]]
-[[GridBagLayoutの使用>Swing/GridBagLayout]]

**コメント [#r1874ae6]
#comment