Swingコントロールの入力値をリアルタイムチェック

DocumentFilterを使った便利な入力値チェッククラスがあったが、残念ながら整数値限定だったので、複数型に対応させてみた。

public abstract class ValueDocumentFilter extends DocumentFilter {

	protected abstract void parse(String proposedValue);

	@Override
	public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
		if(string == null) {
			return;
		} else {
			replace(fb, offset, 0, string, attr);
		}
	}

	@Override
	public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
		replace(fb, offset, length, "", null);
	}

	@Override
	public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
		Document doc = fb.getDocument();
		int currentLength = doc.getLength();
		String currentContent = doc.getText(0, currentLength);
		String before = currentContent.substring(0, offset);
		String after = currentContent.substring(length+offset, currentLength);
		String newValue = before + (text == null ? "" : text) + after;
		checkInput(newValue, offset);
		fb.replace(offset, length, text, attrs);
	}

	private void checkInput(String proposedValue, int offset) throws BadLocationException {
		if(proposedValue.length() > 0) {
			try{
				//newValue = Integer.parseInt(proposedValue);
				parse(proposedValue);
			} catch(NumberFormatException e) {
				throw new BadLocationException(proposedValue, offset);
			}
		}
	}
}

使い方は以下の通りです。

JTextField tf = new JTextField();
// 整数に限定する場合
((AbstractDocument)tf.getDocument()).setDocumentFilter(
	new ValueDocumentFilter() {
		protected void parse(String proposedValue) {
			Integer.parseInt(proposedValue);
		}
	}
);
// 実数に限定する場合
((AbstractDocument)tf.getDocument()).setDocumentFilter(
	new ValueDocumentFilter() {
		protected void parse(String proposedValue) {
			Double.parseDouble(proposedValue);
		}
	}
);

下記サイトを参考にさせて頂きました。
有難うございました。
http://terai.xrea.jp/Swing/NumericTextField.html

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です