画面上にボタンなどの部品を配置する際に使用するレイアウトアルゴリズムには下記のものなどがあります。
FlowLayout は、左上から右下に向けて、部品を流し込むようにレイアウトします。HTML で文字や画像を流し込むのに似ています。
setLayout(new FlowLayout());
add(b1);
add(b2);
add(b3);
GridLayout は、画面を n×m の格子に分割し、それぞれの升目に部品をレイアウトします。
setLayout(new GridLayout(2, 3));
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
GridBagLayout を用いることで、画面を n×m の升目に分割し、(0, 0) の座標から幅 1、高さ 3 の部品を配置することができます。
GridBagLayout gbl = new GridBagLayout();
void addButton(Button b, int x, int y, int w, int h) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
gbl.setConstraints(b, gbc);
add(b);
}
Test() {
:
setLayout(gbl);
addButton(b1, 0, 0, 1, 3); // (0, 0) 幅=1, 高さ=3
addButton(b2, 1, 0, 1, 1); // (1, 0) 幅=1, 高さ=1
addButton(b3, 1, 1, 1, 1); // (1, 1) 幅=1, 高さ=1
addButton(b4, 1, 2, 1, 1); // (1, 2) 幅=1, 高さ=1
:
}
BorderLayout は、画面を上下左右中の 5つのブロックに分け、それぞれに部品を配置します。5つのブロックはそれぞれ、東西南北中央(East, West, South, North, Center)で示されます。
setLayout(new BorderLayout());
add("North", b1);
add("East", b2);
add("South", b3);
add("West", b4);
add("Center", b5);
CardLayout は、複数の部品をカードのスタックとして保持し、一番最初のカードだけを画面に表示します。カードを入れ替えるには next()、previous()、first()、last()、show() などのメソッドを用います。
CardLayout cl = new CardLayout();
setLayout(cl);
add("b1", b1);
add("b2", b2);
add("b3", b3);
cl.show(this, "b2");
BoxLayout は Swing で追加されたレイアウトで、部品を単純に横方向または縦方向にならべていきます。横方向の場合、画面の横幅が狭くなっても自動改行されない点が FlowLayout と異なります。
setLayout(new BoxLayout(this, BoxLayout.X_AXIS);
add(b1);
add(b2);
add(b3);
パネル(Panel)は、ボタンなどの部品や他のパネルを乗せることができる無地の板です。パネルを用いることで、柔軟なレイアウトが可能になります。下記の例では、フレームを左右に分割してそれぞれにパネル p1、p2 を貼り付けています。さらに、p1 には b1 を、p2 には b2、b3、b4 を貼り付けています。
import java.awt.*;
public class Test extends Frame {
Panel p1 = new Panel();
Panel p2 = new Panel();
Button b1 = new Button("B1");
Button b2 = new Button("B2");
Button b3 = new Button("B3");
Button b4 = new Button("B4");
public Test() {
super("Test");
setLayout(new GridLayout(1, 2));
add(p1);
add(p2);
p1.setLayout(new GridLayout(1, 1));
p2.setLayout(new GridLayout(3, 1));
p1.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(b4);
setSize(300, 200);
show();
}
public static void main (String args []) {
new Test();
}
}