学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Javaプログラミング入門その35 テキストコンポーネントの利用

>>この記事には書き直した新しいページがあります。<<


<<前  [TOP]  次>>


今回は、入力可能なTextComponent系とダイアログ、ファイルダイアログを扱います。


まずは以下のサンプルプログラムを作成してみましょう。


【AwtTextTest.java】

/**
*いろいろなTextComponent
*/

import java.awt.*;
import java.awt.event.*;

public class AwtTextTest implements ActionListener {

	private Panel tfPanel, taPanel;
	private TextField tf1, tf2;
	private TextArea ta;

	/**コンストラクタ*/
	public AwtTextTest() {

		Label label1 = new Label("Password");
		Label label2 = new Label("Input Text");

		//10桁でテキストフィールドを生成。エコーする文字は「*」」
		tf1 = new TextField(10);
		tf1.setEchoChar('*');

		//10桁でテキストフィールドを生成。初期文字列「Hello」
		tf2 = new TextField("Hello", 10);

		//Label,TextFieldをPanelに配置
		tfPanel = new Panel();
		tfPanel.add(label1);
		tfPanel.add(tf1);
		tfPanel.add(label2);
		tfPanel.add(tf2);

		//テキストエリアの生成
		ta = new TextArea(3, 40);		//3行×40桁
		ta.setBackground(Color.black);	//TextCompornentで定義
		ta.setEditable(false);		//編集は不可

		taPanel = new Panel();
		taPanel.add(ta);

		//イベント通知登録
		tf1.addActionListener(this);
		tf2.addActionListener(this);
	}

	/**TextFieldでEnterが押されたときの処理*/
	public void actionPerformed(ActionEvent evt) {

		Object obj = evt.getSource();

		if (obj.equals(tf1)) {

			//色の変更(Componentで定義)
			tf2.setForeground(Color.red);

			//文字列の設定
			tf2.setText(tf1.getText());
			ta.setForeground(Color.red);

			//文字列を追加
			ta.append(tf2.getText() + "\n");
		}


		else if (obj.equals(tf2)) {

			tf2.setForeground(Color.black);
			ta.setForeground(Color.white);
			ta.append(tf2.getText() + "\n");
		}
	}

	/**main()*/
	public static void main(String[] args) {

		AwtTextTest test = new AwtTextTest();
		MyFrame frame = new MyFrame("TextTest");
		frame.add(test.tfPanel, "Center");
		frame.add(test.taPanel, "South");
		frame.pack();
		frame.setVisible(true);
	}
}



テキストコンポーネントは編集可能なテキストを表示するためのものです。
編集の可否や文字色・入力されたテキストの内容・キャレット(カーソル)位置などの設定や取得といった多くのことが可能ですが、実際の使用には、子クラスであるTextFieldやTextAreaを活用します。


一行入力を行う場合には、テキストフィールド(TextField)を使用します。

TextField tfd1 = new TextField();    //新しいテキストフィールドを生成
TextField tfd2 = new TextField(6);    //桁数を指定して生成
TextField tfd3 = new TextField("test");    //文字列を指定して生成
TextField tfd4 = new TextField("test", 10);    //文字列と桁数を指定



ただし、指定する桁数による文字列幅は目安程度です。
また、「setEchoChar('1 文字')」でエコー文字(表示される文字)を指定することでパスワード入力のように扱うことも可能です。
文字列の設定には「setText(String)」を利用します。
また、内容の取得はTextComponentで定義された「getText()」を用います。

tf2.setEchoChar('*');    //TextField tf2の表示文字を*に設定
tf1.setText("test");    //TextField tf1 に文字列を設定
String str = tf1.getText();    //TextField tf1 の内容をstrに代入



TextFieldで「Enter」キーが押されるとActionEventが発生して、ActionListenerに通知されます。
イベント処理は「actionPerformed()」に記述します。

public class Test implements ActionListener {

    /**コンストラクタ*/
    public Test() {
        :
         TextField tf = new TextField("test");
        tf.addActionListener(this);    //イベント通知の登録
             :
     }

    /**「Enter」キーが押されたときの処理*/
    public void actionPerformed(ActionEvent evt) {
        //処理
     }
}

また、TextFieldでキーを押すたびにKeyEventが送られるので、必要ならそれら情報を取得することも可能です。
リスナはKeyListener、メソッドはkeyPressed()、keyReleased(), keyType()。


複数行の表示(入力)を行うテキストコンポーネントはテキストエリア(TextArea)です。

TextArea ta1 = new TextArea();    //新しいテキストエリアを生成
TextArea ta2 = new TextArea(40, 80);    //行と桁を指定して生成
TextArea ta3 = new TextArea("test");    //文字列を指定して生成
TextArea ta4 = new TextArea("test", 40, 80);    //文字列と行・桁を指定

//文字列と行・桁を指定。両方のスクロールバーを表示
TextArea ta5 = new TextArea("test", 40, 80, TextArea.SCROLLBARS_BOTH);    

ここでも指定している桁数による文字幅は目安程度です。
文字列の設定にはTextComponentで定義されている「setText(String)」がありますが、TextAreaでは「insert(String, int 位置)」や「append(String)」を用いて、文字列の挿入を行うことが出来ます。

TextArea ta = new TextArea();
ta.append("test");    //文字列の末尾に「test」を追加



文字列の編集を許可しない場合は「setEditable(boolean)」で「false」に設定してください。

TextArea ta = new TextArea();
ta.setEditable(false);    //編集は不可 



では実行してみましょう。
前回作成した[MyFrame.java]を利用していますのでクローズボタンを使って終了できます。
Passwordと書かれたテキストエリアに文字を入力すると*で隠れます。
エンターを押すと、InputTextエリアに赤色で文字が表示され、Textエリアにも赤色で文字が出力されます。
InputTextエリアに文字を入力し、エンターを押すと、テキストエリアに白色で文字が出力されます。








次のサンプルプログラムを作成してみましょう。


【AwtDialogTest.java】

/**
*Dialogを表示
*/

import java.awt.*;
import java.awt.event.*;

public class AwtDialogTest implements ActionListener {

	private Button showButton, hideButton;
	private Dialog dialog;

	/**コンストラクタ*/
	public AwtDialogTest() {

		//パネルにボタンを配置
		Panel panel = new Panel();
		showButton = new Button("show Dialog");
		hideButton = new Button("Hide Dialog");
		panel.add(showButton);
		panel.add(hideButton);

		//イベント通知登録
		showButton.addActionListener(this);
		hideButton.addActionListener(this);

		//フレームを生成して、コンポーネントを配置
		MyFrame frame = new MyFrame("DialogTest");
		frame.add(panel, "Center");
		frame.pack();
		frame.setVisible(true);

		//ファイルダイアログの生成
		dialog = new Dialog(frame, "Dialog");
		Label label = new Label("Test Dialog");
		dialog.add(label);
		dialog.pack();
	}

	/**ボタンが押されたときの処理*/
	public void actionPerformed(ActionEvent evt) {

		Object obj = evt.getSource();

		if (obj.equals(showButton)) {

			dialog.setVisible(true);	//ダイアログを表示
		}

		else if (obj.equals(hideButton)) {

			dialog.setVisible(false);	//ダイアログを非表示
		}
	}

	/**main()*/
	public static void main(String[] args) {

		new AwtDialogTest();
	}
}



通常、システムからの知らせに応じてユーザーが反応する場合、例えば、システムからの「本当にファイルを消しても良いですか?」に対する反応で「はい」「いいえ」を選択場合は、「ダイアログウィンドウ」と呼ばれるもので表示します。
AWTでダイアログウィンドウを生成する際は、Dialogクラスを使用します。
Dialogの生成には親となるFrameかDialogを指定する必要があります。
また、初期設定されているレイアウトはボーダーレイアウトで、フレームと同様にコンポーネントを配置することが出来ます。

Frame frame = new Frame();
Label label = new Label("ラベル");

//frameをオーナーとしてタイトル付で生成(タイトル無しでも生成可)
Dialog dialog = new Dialog(frame, "知らせ");
dialog.add(label, "Center");    //ラベルをダイアログに設定
dialog.pack();    //最小範囲で最適化

設定によってはダイアログが表示中は他のウィンドウの入力が出来ないようにすることも可能です。


ファイルダイアログはDialogの子クラスです。
ファイルの選択に必要なディレクトリの表示や「OK」「キャンセル」などGUIでファイル選択が可能になり、選択するまでは他の入力は出来ないようになっています。
ダイアログの内容はモード(LOAD, SAVE)によって切り替わります。
GUI部分はもちろんですが、「ファイルの上書き」動作もシステムに依存します。
Linux上では上書きの確認は求められないので、誤ってファイルを上書きしないように十分に注意してください。
インスタンス生成時はそのファイルダイアログを所有するフレームを指定してください。
さらにタイトルやモードを指定して生成することも出来ます。

FIleDialog fd = new FileDialog(frame);



生成したFileDialogの利用例

fDialog.setTitle("Load");    //ダイアログにタイトル設定
fDialog.setMode(FileDialog.LOAD);    //ファイルダイアログをロード用に設定
fDialog.setVisible(true);    //ファイルダイアログを表示
fName = fDialog.getFile();    //ファイルが選択された場合のファイル名の取得

if(fName != null) {    //キャンセルが押された場合はnull
    //ファイルがきちんと選択された場合の処理
} 



「setDirectory(String)」で表示されるディレクトリを設定することも出来ます。
ディレクトリの取得は「String getDirectory()」です。


では、プログラムを実行してみましょう。
前回作成した[MyFrame.java]を利用していますのでクローズボタンを使って終了できます。
ShowDialogボタンを押すと、文字が書かれたダイアログが現れます。
Hide Dialogボタンを押すと、現れたダイアログが消えます。








以下のサンプルプログラムを作成してみましょう。


【AwtMiniEditor.java】

/**
*FileDialogを利用したテキストエディタ
*/

import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class AwtMiniEditor implements ActionListener {

	private Button loadButton, saveButton;
	private TextArea ta;
	private FileDialog fDialog;

	/**コンストラクタ*/
	public AwtMiniEditor() {

		//パネルにボタンを配置
		Panel panel = new Panel();
		loadButton = new Button("Load");
		saveButton = new Button("Save");
		panel.add(loadButton);
		panel.add(saveButton);

		//テキストエリアの生成(スクロールバーは垂直方向のみ)
		ta = new TextArea("", 20, 80, TextArea.SCROLLBARS_VERTICAL_ONLY);
		ta.setBackground(Color.white);

		//イベント通知登録
		loadButton.addActionListener(this);
		saveButton.addActionListener(this);

		//フレームを生成して、コンポーネントを配置
		MyFrame frame = new MyFrame("MiniEditor");
		frame.add(panel, "Center");
		frame.add(ta, "South");
		frame.pack();
		frame.setVisible(true);

		//ファイルダイアログの生成
		fDialog = new FileDialog(frame);

	}

	/**ボタンが押されたときの処理*/
	public void actionPerformed(ActionEvent evt) {

		Object obj = evt.getSource();
		String fName;

		if(obj.equals(loadButton)) {

			//ファイルダイアログをロード用に設定
			fDialog.setTitle("Load");
			fDialog.setMode(FileDialog.LOAD);
			
			//ファイルダイアログを表示
			fDialog.setVisible(true);

			//ファイルが選択された場合のファイル名の取得
			fName = fDialog.getFile();

			//キャンセルが押された場合はnull
			if (fName != null) {

				//テキストエリアをクリア
				ta.setText("");
				loadFile(fName);
			}
		}
		else if (obj.equals(saveButton)) {

			//ファイルダイアログをセーブ用に設定
			fDialog.setTitle("Save");
			fDialog.setMode(FileDialog.SAVE);
			
			fDialog.setVisible(true);
			fName = fDialog.getFile();

			if (fName != null) {

				saveFile(fName);
			}
		}
	}

	/**読み込み処理*/
	public void loadFile(String fileName) {

		BufferedReader inFile;

		try {

			//FileReaderを生成してからBufferedReaderを生成
			inFile = new BufferedReader(new FileReader(fileName));

			String line;

			//1行ずつ読んでは、テキストエリアに書き込み
			while ((line=inFile.readLine()) != null) {

				ta.append(line + "\n");
			}
			inFile.close();

		}
		catch(FileNotFoundException ex) {	//ファイルがない場合の処理

			System.err.println(ex);

		}
		catch(IOException ex) {
			System.err.println(ex);
			System.exit(1);
		}
	}

	/**ファイル書き込みのメソッド*/
	public void saveFile(String fileName) {

		BufferedWriter outFile;	//バッファリングを使用して書き込み

		try {

			//FileWriterを生成してからBUfferedWriterを生成
			outFile = new BufferedWriter(new FileWriter(fileName));
			outFile.write(ta.getText());		//書き込み
			outFile.flush();
			outFile.close();			//クローズ
		}
		catch (IOException ex) {

			System.err.println(ex);
			System.exit(1);
		}
	}

	/**main()*/
	public static void main(String[] args) {

		new AwtMiniEditor();
	}
}



では早速実行してみましょう。
前回作成した[MyFrame.java]を利用していますのでクローズボタンを使って終了できます。
ファイルのロード、セーブ、書き替えが出来ます。








<<前  [TOP]  次>>