| ■swingコンポーネント->JPanel | ||||
| パネルはコンポーネントを入れるための中間コンテナです。いくつかのコンポーネントをまとめてパネルに配置することでグループとして扱え、全体の配置をしやすくなります。また、通常のレイアウトだけだと複雑な画面構成ができませんが、パネルを使用することで可能になります。 | ||||
|
|
||||
| コンストラクタ(抜粋) | ||||
|
||||
| メソッド(抜粋) | ||||
|
||||
| PanelSample1.java | ||||
| import java.awt.*; | ||||
| import java.awt.event.*; | ||||
| public class PanelSample1 extends Frame { | ||||
| static final int NUM = 6; | ← �@変数NUMを定数として宣言 | |||
| Button[] bun1 = new Button[NUM]; | ← �Abtn1を配列で宣言 | |||
| Button btn2 = new Button("btn2"); | ||||
| Button btn3 = new Button("btn3"); | ||||
| Panel pnl = new Panel(); | ← �Bパネルのインスタンス生成 | |||
| public PanelSample1() { | ||||
| super(PanelSample1); | ||||
| addWindowAdapter(new WindowListener() { | ||||
| public void windowClosing(WindowEvent e) { | ||||
| System.exit(0); | ||||
| } | ||||
| }); | ||||
| setSize(400,300); | ||||
| setLocation(100,100); | ||||
| setLayout(new BorderLayout()); | ← �Cウィンドウをボーダーレイアウトに設定 | |||
| pnl.setLayout(new GridLayout(2,3)); | ← �Dパネルをグリッドレイアウトに設定 | |||
| for(int i=0; i<NUM; i++){ | ||||
| btn1[i] = new Button("btn1_"+i); | ← �Ebtn1のインスタンス生成 | |||
| pnl.add(btn1[i]); | ← �Fbtn1[i]をパネルに配置 | |||
| } | ||||
| add(pnl,"Center"); | ← �Gパネルをウインドウに配置 | |||
| add(btn2,"North"); | ||||
| add(btn3,"East"); | ||||
| setVisible(true); | ||||
| } | ||||
| public static void main(String[] args) { | ||||
| PanelSample1 myClass = new PanelSample1(); | ||||
| } | ||||
| } | ||||
| �@static final
int NUM = 6; NUMを定数として定義しています。このときの値は6です。 |
||||
| �A
Button[] bun1 = new Button[NUM]; パネルに乗せるボタンを配列で用意しています。 (※パネルに乗せないボタンを区別するために配列を使いました。) |
||||
| �BPanel pnl =
new Panel(); パネルのインスタンスを生成。 |
||||
| �CsetLayout(new
BorderLayout()); ウィンドウのレイアウトをBorderLayoutに設定しています。 |
||||
| �Dpnl.setLayout(new
GridLayout(2,3)); パネルのレイアウトをGridLayoutに設定しています。 |
||||
| �Ebtn1[i]
= new Button("btn1_"+i); btn1[i]のインスタンスを生成。 今回はfor文の中で処理しています。 |
||||
|
�Fpnl.add(btn1[i]); pnlにbtn1[i]を配置しています。 for文を使うことにより、�E�Fを一回の記述にしています。 |
||||
| �Gadd(pnl,"Center"); btn1を乗せたpnlをウィンドウのCenter位置に配置しています。 |
||||
| もどる | ||||