- Home ›
- Swing ›
- FlowLayoutクラス ›
- HERE
配置されたコンポーネントの表示位置を設定する
配置されたコンポーネントが貼り付けられているパネルやフレームの中でどの位置に表示されるのかを設定する方法を確認します。表示位置を設定するにはコンストラクタで指定する方法とメソッドで指定する方法があります。まずコンストラクタで指定する方法を確認します。
FlowLayout public FlowLayout(int align)
デフォルトの 5 単位の水平間隔と垂直間隔を持つ新しい FlowLayout を指定さ れた配置で構築します。配置引数の値は、FlowLayout.LEFT、FlowLayout.RIGHT、 FlowLayout.CENTER、FlowLayout.LEADING、または FlowLayout.TRAILING のど れかでなければなりません。 パラメータ: align - 配置の値
引数には表示位置を表すint型の値を指定します。指定できる値は次の5つです。
| 値 | 位置 |
|---|---|
| FlowLayout.LEFT | 左詰 |
| FlowLayout.CENTER | 中央(デフォルト) |
| FlowLayout.RIGHT | 右詰端 |
| FlowLayout.LEADING | 左詰 |
| FlowLayout.TRAILING | 右詰 |
※LEADING(先頭)とTRAILING(末)は利用している言語によって位置が変わります。日本語や英語のように左から右へ文字を表示する場合はLEADINGが左詰でTRAILINGが右詰ですが、右から左へ文字を表示するのが普通の言語の場合にはLEADINGが右詰でTRAILINGが左詰となります。
実際の使い方は次のようになります。
FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
メソッドを使って設定する
FlowLayoutクラスのオブジェクトを作成した後でメソッドを使って表示位置を設定することも可能です。FlowLayoutクラスで用意されている「setAlignment」メソッドを使います。
setAlignment public void setAlignment(int align)
このレイアウトの配置を設定します。次の値を指定できます。 FlowLayout.LEFT FlowLayout.RIGHT FlowLayout.CENTER FlowLayout.LEADING FlowLayout.TRAILING パラメータ: align - 配置を指定する上記の値のどれか
引数には表示位置を表すint型の値を指定します。設定できる値はコンストラクタの場合と同じです。
実際の使い方は次のようになります。
FlowLayout layout = new FlowLayout(); layout.setAlignment(FlowLayout.LEFT );
サンプルプログラム
では簡単なサンプルを作成して試してみます。
import javax.swing.*;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
public class FlowLayoutTest3 extends JFrame{
public static void main(String[] args){
FlowLayoutTest3 frame = new FlowLayoutTest3();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(10, 10, 300, 200);
frame.setTitle("タイトル");
frame.setVisible(true);
}
FlowLayoutTest3(){
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JPanel p1 = new JPanel();
p1.setBackground(Color.ORANGE);
p1.add(button1);
p1.add(button2);
JButton button3 = new JButton("Button3");
JButton button4 = new JButton("Button4");
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.LEFT));
p2.add(button3);
p2.add(button4);
JButton button5 = new JButton("Button5");
JButton button6 = new JButton("Button6");
JPanel p3 = new JPanel();
FlowLayout layout = new FlowLayout();
layout.setAlignment(FlowLayout.RIGHT);
p3.setLayout(layout);
p3.add(button5);
p3.add(button6);
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.PAGE_START);
getContentPane().add(p3, BorderLayout.PAGE_END);
}
}
上記をコンパイルした後で実行すると次のように表示されます。
今回は3つのパネルを用意し、それぞれのレイアウトマネージャーをFlowLayoutに設定した後で表示位置を設定してあります。
( Written by Tatsuo Ikura )
JavaDrive