|
||||||||||||||||||||||
|
ホーム > Swing による GUI > BoxLayout (ボックスレイアウト) の基礎 BoxLayout (ボックスレイアウト) の基礎
ボックスレイアウトでは、コンポーネントを縦または横に並べます。
import java.awt.Container;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class LayoutTestBox1 extends JFrame {
public LayoutTestBox1(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,150);
Container contentPane = getContentPane();
setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JButton button1 = new JButton("1 - First");
JButton button2 = new JButton("2 - Second");
JButton button3 = new JButton("3 - Third");
contentPane.add(button1);
contentPane.add(button2);
contentPane.add(button3);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
createAndShowGUI();
}
});
}
protected static void createAndShowGUI() {
LayoutTestBox1 frame = new LayoutTestBox1();
frame.setVisible(true);
}
}
この例では setLayout メソッドに BoxLayout オブジェクトを作成して渡しています。 BoxLayout のコンストラクタで、並べる方向を示す BoxLayout.Y_AXIS (Y 軸方向、すなわち縦方向) を渡しています。 横の場合は X_AXIS を渡します。 左右または上下の整列をしたい場合も、ボックスレイアウトで対応できます。
このスクリーンショットでは、コンポーネントの中央揃えでボタンが並んでいます。 この場合は setAlignmentX メソッドに CENTER_ALIGNMENT を渡すことで、実現できます。
...
Container contentPane = getContentPane();
setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JButton button1 = new JButton("1 - First");
JButton button2 = new JButton("2 - Second");
JButton button3 = new JButton("3 - Third");
button1.setAlignmentX(CENTER_ALIGNMENT);
button2.setAlignmentX(CENTER_ALIGNMENT);
button3.setAlignmentX(CENTER_ALIGNMENT);
contentPane.add(button1);
contentPane.add(button2);
contentPane.add(button3);
...
ホーム > Swing による GUI > BoxLayout (ボックスレイアウト) の基礎 |
|
© 2010 Java 入門 |
|||||||||||||||||||