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

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

Javaプログラミング入門その44 テキストコンポーネントを利用したプログラム

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


<<前  [TOP]  次>>


テキストの入力(あるいは出力)えお行うには、javac.swing.textJTextComponentを基とするテキストコンポーネントを使用します。
具体的には、javax.swingパッケージにある「JTextField」「JPasswordField」「JTextArea」「JTextEditor」「JTextPane」などのクラスを使用します。
今回は上記5種類を使用します。
特徴は以下の通りです。

コンポーネント複数行テキストの種類用途
JTextField×プレーン1行のテキスト入力
JPasswordField×プレーン1行のパスワード入力
(JTextFieldを拡張)
JTextAreaプレーン編集可能な短いドキュメント。
折り返しなどが設定できる。
JEditorPaneプレーン/書式付様々な表示形式を設定できる。
初期状態でサポートされているのはHTML(3.2)とRTF(制限付き)
JTextPane書式付き複数のフォント、画像、コンポーネントなどを使用できる。
(JEditorPaneを拡張)


JTextComponentは、「表示テキスト」「実行できるアクション」「キーマップ」「キャレット」「文字や背景、キャレットの色」などの設定と取得、「コピー」「切り抜き」「貼り付け」の処理などを行うことが出来ます。


JTextComponentで、値を取得するためのメソッドの一部を挙げておきます。
設定は「get○○」の返値を引数とした「set○○」というようになります(返値はvoid)。
例えば、キャレット(カーソル)の色を設定するには「setCaretColor(Color)」となります。
メソッド返値取得されるもの
setCaretColor()Colorキャレット(カーソル)の色
setCaretPosition()intキャレットの位置
setSelectedText()String選択した文字列の内容
getSelectedTextColor()Color選択した文字列の色
getSelectionColor()Color選択した文字列の背景色
getSelectionEnd()int選択した文字列の末尾位置
getSelectionStart()int選択した文字列の開始位置
getText()Stringテキストの内容
isEditable()boolean編集可能か否か
このほかに「copy()」(コピー)、「cut()」(切り取り)、「paste()」(貼り付け)といったメソッドがあります。


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


【SwingJTextTest1.java】

/** JTextField, JPasswordField, JTextAreaのテスト*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingJTextTest1 implements ActionListener {

	private JMenuBar menuBar;
	private JTextField tf;		//テキストフィールド
	private JPanel tfPanel;		//テキストフィールドを配置
	private JPasswordField pf;	//パスワードフィールド
	private JPanel pfPanel;		//パスワードフィールドを配置
	private JTextArea ta;		//テキストエリア
	private JScrollPane sp;		//テキストエリアを配置

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

		//メニューの生成
		menuBar = new JMenuBar();
		JMenu editMenu = new JMenu("Edit");
		JMenuItem copyItem = new JMenuItem("Copy");
		JMenuItem pasteItem = new JMenuItem("Paste");
		editMenu.add(copyItem);
		editMenu.add(pasteItem);
		menuBar.add(editMenu);

		//列数6でテキストフィールドを生成
		tf = new JTextField("test", 6);
		tf.setSelectedTextColor(Color.red);	//選択文字列の色設定
		tf.setActionCommand("text");		//アクションコマンド設定
		
		//テキストフィールドを配置するパネルを生成
		tfPanel = new JPanel();
		tfPanel.add(tf);

		//列数 6でパスワードフィールドを生成
		pf = new JPasswordField(6);
		pf.setEchoChar('?');
		pf.setSelectionColor(Color.yellow);	//選択文字列の背景色設定
		pf.setActionCommand("password");	//アクションコマンド設定

		//パスワードフィールドを配置するパネルを生成
		pfPanel = new JPanel();
		pfPanel.add(pf);

		//テキストエリアの生成
		ta = new JTextArea(10, 20);	//10行×20桁
		ta.setLineWrap(true);		//折り返しあり
		ta.setWrapStyleWord(false);	//文字単位の折り返し
		ta.setTabSize(4);		//TABキーの空白数
		ta.setEditable(true);		//編集可

		//テキストエリアを配置するスクロールペイン
		sp = new JScrollPane(ta);

		//イベント通知を登録
		tf.addActionListener(this);
		pf.addActionListener(this);
		copyItem.addActionListener(this);
		pasteItem.addActionListener(this);
	}

	/**イベント処理*/
	public void actionPerformed(ActionEvent evt) {
		String command = evt.getActionCommand();

		//アクションコマンドに応じた処理
		if(command.equals("text")) {
			ta.append(tf.getText() + "\n");		//テキストエリアに追加
		}
		else if(command.equals("password")) {
			ta.append(new String(pf.getPassword()) + "\n");
		}
		else if(command.equals("Copy")) {
			tf.copy();	//テキストフィールドをコピー
		}
		else if(command.equals("Paste")) {
			pf.paste();	//パスワードフィールドへ張り付け
		}
	}



	/**main()*/
	public static void main(String[] args) {
		SwingJTextTest1 sample = new SwingJTextTest1();

		JFrame frame = new JFrame("JTextTest1");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setJMenuBar(sample.menuBar);
		frame.getContentPane().add(sample.tfPanel, "North");
		frame.getContentPane().add(sample.pfPanel, "Center");
		frame.getContentPane().add(sample.sp, "South");
		frame.pack();
		frame.setVisible(true);
	}
}



1行入力を行う場合には、JTextFieldを使用します。

JTextField tf1 = new JTextField();    //新しいテキストフィールドを生成
JTextField tf2 = new JTextField(6);    //桁数を指定して生成
JTextField tf3 = new JTextField("test");    //文字列を指定して生成
JTextField tf4 = new JTextField("test", 10);    //文字列と桁数を指定



ただし、指定する桁数は「m」(最も幅が広いと思われる文字)にあわせたものですので、実際には目安程度と考えてください。


テキストフィールドに表示する文字列のは位置の指定は、「setHorizontalAlignment()」を使用します。
使用できる定数は、JTextFieldの「LEFT」「CENTER」「RIGHT」「LEADING」(左から右に記述する場合は左端)「TRAILING」(左から右に記述する場合は右端)です。

JTextField tf1 = new JTextField();    //新しいテキストフィールドを生成
tf1.setHorizontalAlignment(JTextField.CENTER);



テキストフィールドのイベントは、基本的にはActionListenerを利用して、actionPerformed()メソッドに処理を記述すればよいです。
この場合、コンポーネントで「Enter」キーが押されることで「イベントの発生」となります。
「getText()」でテキストを取得すればよいです。


1行入力で、内容が表示されないようにするには、JPasswordFieldを使用します。
JPasswordFieldは、JTextFieldを拡張したものなので、JTextFieldと同様に使用できます。

JPasswordField pf = new JPasswordField(6);    //桁数を指定して生成



表示される文字の初期設定は「*」ですが、「setEchoChar('文字')」で他の文字にも変更できます。

JPasswordField pf = new JPasswordField();
pf.setEchoChar('?');    //表示文字は「?」



パスワードフィールドの値を取得する場合は、「getText()」(返値はString)ではなく、「getPassword()」(返値はchar[])が推奨されています。
String型として扱うには以下のようにします。

JPasswordField pf = new JPasswordField();
String str = new String(pf.getPassword());    //char[]をStringに

複数行の表示(入力)を行うシンプルなテキストコンポーネントは、JTextAreaです。

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



JTextAreaでは、「折り返し処理」(1行に収まらないテキストを次行に表示するかどうか)、「単語での折り返し処理」(英単語などが行末で分断される場合、そのまま表示するか、次行の先頭から表示するか)、「タブの幅」(初期設定は「8」)などを設定できます。

JTextArea ta = new JTextArea();    //新しいテキストエリアを生成
ta.setLineWrap(true);    //折り返しあり
ta.setWrapStyleWord(true);    //単語での折り返しをする
ta.setTabSize(4);    //タブは4桁



文字列の挿入は、「insert(String, int 位置)」や「append(String)」を用います。

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



では、サンプルプログラムを実行してみましょう。
テキストフィールドとパスワードフィールドに入力が出来ます。
入力してENTERを押すとテキストエリアに表示されます。
テキストフィールドにはデフォルトで「test」と表示されています。
メニューからコピーとペーストが出来ます。








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


【SwingJEditorPaneTest1.java】

/** JEditorPaneのテスト*/

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

public class SwingJEditorPaneTest1 implements ActionListener, HyperlinkListener {

	private JMenuBar menuBar;
	private JEditorPane editorPane;
	private JScrollPane sp;		//エディタペインを配置
	private JMenuItem openItem, saveItem;
	private JFileChooser fileChooser;


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

		//ファイルチューザーの生成
		fileChooser = new JFileChooser(".");
		fileChooser.setDialogTitle("file");

		//メニューの生成
                menuBar = new JMenuBar();
                JMenu fileMenu = new JMenu("FILE");
                openItem = new JMenuItem("Open");
                saveItem = new JMenuItem("Save");
                fileMenu.add(openItem);
                fileMenu.add(saveItem);
                menuBar.add(fileMenu);

		//エディタペインの生成
		editorPane = new JEditorPane();
		editorPane.setEditable(true);	//編集可

		//エディタペインを配置するスクロールペインを生成
                sp = new JScrollPane(editorPane);
	
		//イベント通知を登録
                openItem.addActionListener(this);
                saveItem.addActionListener(this);
		
		//編集不可の時のハイパーリンク処理のためイベント通知の登録
		editorPane.addHyperlinkListener(this);
	}

	/**イベント処理*/
	public void actionPerformed(ActionEvent evt) {
                String command = evt.getActionCommand();

		//アクションコマンドに応じた処理
                if(command.equals("Open")) {
			openFile();	//読み込み処理
                }
		else if(command.equals("Save")) {
			saveFile();	//保存処理
                }
	}

	/**ハイパーリンクに対応するイベント処理*/
	public void hyperlinkUpdate(HyperlinkEvent evt) {

		//ハイパーリンク上でクリック
		if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
			try {
				//ハイパーリンクのURLを得てページ表示
				editorPane.setPage(evt.getURL());
			}
			catch (IOException ex) {
				System.err.println(ex);
			}
		}
	}

	/**ファイルが開かれた時の処理*/
	public void openFile() {
		int state = fileChooser.showOpenDialog(null);
		File file = fileChooser.getSelectedFile();

		if(file != null && state == JFileChooser.APPROVE_OPTION) {
			try{
				editorPane.setPage("file:"+file.getAbsolutePath());
			}

			catch(Exception ex) {
				System.err.println(ex);
			}
		}
		else if(state == JFileChooser.CANCEL_OPTION){
			return;
		}
		else if(state == JFileChooser.ERROR_OPTION){
			JOptionPane.showMessageDialog(null, "Error!");
		}
	}

	/**ファイルに保存する*/
	public void saveFile() {
		int state = fileChooser.showSaveDialog(null);
		File file = fileChooser.getSelectedFile();

		if(file != null && state == JFileChooser.APPROVE_OPTION) {

			//ファイル書き込みメソッドへ
			writeFile(file.getAbsolutePath());
		
			//書き込んだ内容を再表示
			try{
                                editorPane.setPage("file:"+file.getAbsolutePath());
                        }
                        catch(Exception ex) {
                                System.err.println(ex);
                        }
                }
                else if(state == JFileChooser.CANCEL_OPTION){
                        return;
                }
                else if(state == JFileChooser.ERROR_OPTION){
                        JOptionPane.showMessageDialog(null, "Error!");
                }
	}

	/**ファイルの書き込みのメソッド*/
	public void writeFile(String fileName){
		BufferedWriter outFile;	//バッファリングを使用して書き込み

		try {
			//FileWriterを生成してからBufferedWriterを生成→書き込み
			outFile = new BufferedWriter(new FileWriter(fileName));
			outFile.write(editorPane.getText());
			outFile.close();
		}
		catch(IOException iox) {
			System.err.println(iox);
		}
	}

	/**main()*/
	public static void main(String[] args) {
		SwingJEditorPaneTest1 sample = new SwingJEditorPaneTest1();

		JFrame frame = new JFrame("JEditorPaneTest1");
		frame.setSize(600, 400);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setJMenuBar(sample.menuBar);
		frame.getContentPane().add(sample.sp);
                frame.setVisible(true);
	}
}



JEditorPaneは、通常のテキストの他に、HTML(3.2)やRTF(制限付き)形式で文書を表示します。

JEditorPane ep1 = new JEditorPane();    //新しいエディタペインを生成

//URLを指定して生成
JDditorPane ep2 = new JEditorPane("http://www.URL.ne.jp/index.html");



文章をそのように表示するかは、インストールされている「EditorKit」によって決まります。
EditorKitは「setEditorKit(EditorKit)」で設定できます。

通常のテキスト(text/plain)DefaultEditorkitの拡張
HTML(text/html)javax.swing.text.html.HTMLEditorKitクラス
RTF形式(text/rtf)javax.swing.text.rtf.RTFEDitorKitクラス


これらの形式の文章をロードするには、以下のようなメソッドを使用します。
setText(String)文字列から生成。
現在のEditorKitが使われる
read(InputStream, Object)readerから生成。
現在のEditorKitが使われる。
<base>タグなどが使用されていないとイメージなどの相対参照が出来ない。
setPage(URL)URLから生成。
URLから自動的に判断される適切なEditorKitが使用される。


setPage()の使用例

JEditorPane = new JEditorPane();

//自動的に、HTMLタグを理解した表示になる
ep.setPage("http://URL.ne.jp/index.html");



エディタペインでは、javax.swing.event.HyperlinkListenerを利用することにより、「編集不可」の場合にハイパーリンクを有効にさせることが出来ます。
イベントが発生した場合には、hyperlinkupdate(HyperlinkEvent)で処理されます。

import javax.swing.event.*;

 public class Sample implements HyperlinkListener {

    JEditorPane ep = new JEditorPane();
    ep.addHyperlinkListener(this);    // ハイパーリンクのイベント通知登録

     public void hyperlinkUpdate(HyperlinkEvent evt) {
        //ハイパーリンク上でクリックされたときの処理
         if (evt.getEventType() ==
            HyperlinkEvent.EventType.ACTIVATED) {

            try {
                //ハイパーリンクのURLを得てページ表示
                 ep.setPage(evt.getURL());
            }
            catch(IOException ex) {
                System.err.println(ex);
            }
        }
    }
}



では、サンプルプログラムを実行してみましょう。
テキストファイルのオープン、編集、セーブが出来ます。








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


【SwingJTextPaneTest.java】

/**JTextPaneのテスト*/

import javax.swing.*;

public class SwingJTextPaneTest {

	private JScrollPane sp;	//テキストペインを配置

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

		//カラーチューザーの生成
		JColorChooser cc = new JColorChooser();

		//イメージの生成
		ImageIcon image = new ImageIcon("char0.gif");

		//テキストペインの生成
		JTextPane textPane = new JTextPane();
		textPane.setEditable(true);	//編集可
		textPane.insertComponent(cc);	//カラーチューザーを挿入
		textPane.insertIcon(image);	//イメージを挿入

		//テキストペインを配置するスクロールペインを生成
		sp = new JScrollPane(textPane);
	}

	/**main() */
	public static void main(String[] args) {
		SwingJTextPaneTest sample = new SwingJTextPaneTest();
		
		JFrame frame = new JFrame("JTextPaneTest");
		frame.setSize(600,400);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 		frame.getContentPane().add(sample.sp);
                frame.setVisible(true);
	}
}



なお、このプログラムを実行するには、以下の「char0.gif」が必要ですので、プログラムを作成するフォルダに保存しておいてください。
[char0.gif]


JTextPaneは、JEditorPaneを拡張したクラスで、さらにイメージアイコンやコンポーネントを表示(編集)することが出来ます。

JTextPane tp1 = new JTextPane();    //新しいテキストペインを生成

//ドキュメントモデルを指定
JTextPane tp2 = new JTextPane(StyledDocument);



イメージの挿入は「insertIcon(Icon)」で行い、コンポーネントの挿入は「insertComponent(Component)」で行います。

JTextPane tp = new JTextPane();    //新しいテキストペインを生成
tp.insertComponent(new JLabel("ラベル"));    //コンポーネントの挿入
tp.insertIcon(new ImageIcon("sample.jpg"));    //イメージの挿入



では、サンプルプログラムを実行してみましょう。
いろいろな色の表示テストが出来ます。








<<前  [TOP]  次>>