●実行中にユーザーから文字列データを受け取る方法と、グリッドレイアウトを勉強します。
●4つのボタンで作ったColorSelect.javaを変更し、2つのテキスト入力と、ラベルと、ボタンに変えます。
●プログラム中の4カ所にあるColorSelectをCatTextに変えます。
public class ColorSelect extends JFrame{ など
↓
public class CatText extends JFrame{ など
●4つのボタンを次のようにします。ここはオブジェクト名の宣言です。JTextFieldがテキストを入力する1行の枠です。
JButton button1; JButton button2; JButton button3; JButton button4;
↓
JTextField text1; JTextField text2; JLabel label; JButton button1;
●次に示すのはコンストラクタの最初の部分、ボタンのオブジェクトを作る部を変えます。JTextFieldの( )にある数字は長さ(横幅)です。
button1 = new JButton("赤"); button2 = new JButton("青"); button3 = button4 =
↓
text1 = new JTextField(10); text2 = new JTextField(10); label = new JLabel(""); button1 = new JButton("OK");
●次に示すのはレイアウトマネージャの部分です。これはグリッドレイアウトにします。
setLayout(new FlowLayout()); //フローを指定 add(button1); add(button2); add(button3); add(button4);
↓
setLayout(new GridLayout(4,1,0,0)); //グリッドを指定 add(text1); add(text2); add(label); add(button1);
●グリッドは縦横の升目をつくりその中に順に入れていくレイアウトです。( )の中は次のような意味です。
GridLayout(行数(y),列数(x),左右の隙間,上下の隙間));
●つぎに示すのはaddActionListenerへの登録です。今回はボタンだけにしておきます。
button1.addActionListener(this); button2.addActionListener(this); button3.addActionListener(this); button4.addActionListener(this);
↓
button1.addActionListener(this);
●次はクリックされたときの動作を決める部分actionPerformed()です。やはりボタンひとつだけになります。
if (e.getSource() == button1) { setBackground(new Color(255,0,0)); } else if (e.getSource() == button2) { //2つ目の色 } else if (e.getSource() == button3) { //3つ目の色 } else if (e.getSource() == button4) { //4つ目の色 }
↓
if (e.getSource() == button1) { label.setText( text1.getText() + text2.getText() ); }
●処理の内容は
text1.getText() text1に現在表示されている文字列を取り込んで text2.getText() text2に現在表示されている文字列を取り込んで
+ 連結して、
label.setText( ); labelの文字列として設定する。