私は、入力として長くかかるJTextFieldのTextValueChangedハンドラを書いています。ユーザは、0とLong.MAXの間の有効な値を入力するだけで済みます。ユーザーが無効な文字を入力すると、JTextFieldの値が常に有効な長さになるように、ユーザーは無効な文字を入力する必要があります。クリーナーはJTextField入力を「サニタイズ」しますか?
私の現在のコードはこのように見えますが、醜いようです。外部のlib(Apache Commonsを含む)がない場合、これを行うためのよりクリーンで簡単な方法がありますか?
public void textValueChanged(TextEvent e) {
if (e.getSource() instanceof JTextField) {
String text = ((JTextField) e.getSource()).getText();
try {
// Try to parse cleanly
long longNum = Long.parseLong(text);
// Check for < 1
if (longNum < 1) throw new NumberFormatException();
// If we pass, set the value and return
setOption("FIELDKEY", longNum);
} catch (NumberFormatException e1) {
// We failed, so there's either a non-numeric or it's too large.
String s = ((JTextField) e.getSource()).getText();
// Strip non-numeric characters
s = s.replaceAll("[^\\d]", "");
long longNum = -1;
if (s.length() != 0) {
/* Really ugly workaround for the fact that a
* TextValueChanged event can capture more than one
* keystroke at a time, if it's typed fast enough,
* so we might have to strip more than one
* character. */
Exception e3;
do {
e3 = null;
try {
// Try and parse again
longNum = Long.parseLong(s);
} catch (NumberFormatException e2) {
// We failed, so it's too large.
e3 = e2;
// Strip the last character and try again.
s = s.substring(0, s.length() - 1);
}
// Repeat
} while (e3 != null);
}
// We parsed, so add it (or blank it if it's < 1) and return.
setOption("FIELDKEY", (longNum < 1 ? 0 : longNum));
}
}
}
フィールドは常にちょうどそのコールに渡し、「ストア」にその値が、getOptionコマンド(キー)呼び出しから再作成されます。
代わりに 'JFormattedTextField'を使用すると何が問題になりますか? – user1329572
私はそれをすることができましたが、それは私の好きなものとは一致しません。フォーカスが失われた場合は、変更を失い、以前に保存したテキスト(望ましくない)に戻すか、無効なテキストを保存します(これも不要です)。 この動作を強制するには、私はそれをオーバーライドして、別のイベントでいくつかのコードを書かなければなりません。 – Charles
'JFormattedTextField'の問題は、あなたが好きなものを入力できることです。テキストフィールドを終了して初めて、検証が行われます。 –