解答例 - 実習課題3 - 10.テキスト・コンポーネント
(実習課題3)
以下のプログラムを作成しなさい。
- ウィンドウに含まれるコンポーネントはテキストフィールド1つ。そのテキストフィールドが持つ特徴は以下のとおり。
- 4文字までしか入力する事ができない。
- 「a」を入力しようとすると、「b」が入力される。
- 文字を削除しようとすると、その左となりの文字が削除される。
- 「Document」インタフェースを利用して作成する事。
- (ヒント)「remove」メソッドを実装する事。
解答例
/**
* DocumentExample.java
* TECHSCORE Javaユーザインタフェース10章 実習課題3
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.ui.chapter10.exercise3;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class DocumentExample extends JFrame {
private JTextField textField;
private MyDocument doc;
public DocumentExample() {
super("DocumentExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
//テキストフィールドを作成
doc = new MyDocument();
textField = new JTextField(doc, "", 5);
getContentPane().add(textField, BorderLayout.CENTER);
pack();
}
public class MyDocument extends PlainDocument {
public MyDocument() {
super();
}
public void insertString(int offset, String text, AttributeSet attributes) throws BadLocationException {
text = text.replace('a', 'b');
text = text.replace('A', 'B');
for (int i = 0; i < text.length(); i++) {
if (this.getLength() > 3) {
return;
}
super.insertString(offset + i, text.substring(i, i + 1), attributes);
}
}
public void remove(int offs, int len) throws BadLocationException {
if (offs == 0) {
return;
}
super.remove(offs - 1, len);
}
}
public static void main(String args[]) {
new DocumentExample().setVisible(true);
}
}

