どのように同じ値としてユーザーから見JFormattedTextField?
-
18-09-2019 - |
質問
を使用してい NumberFormatter
や JFormattedTextField
, ものの、 .getValue()
なと同じ値を返し、ユーザーです。
と思い、入力-文字列が構文解析を用いNumberFormats解析-方法を取得しまNumberformatから NumberFormat.getNumberInstance();
実際のロケールです。でも、おいしい簡単にでも自分で解析-方法は?
例, ている場合、ユーザーの種類 1234.487
の getValue()
戻ります:1234.487
が、ユーザに表示されます 1,234.49
別の例, 使用し、 NumberFormat.getCurrencyInstance();
.ユーザ種類 1234.487
の getValue()
戻ります 1234.487
が、ユーザに表示されます $1,234.49
代わりに, たいと思い、ParseException発生する場合、フォーマッタをできない形式の価値が丸め.その場合、ユーザーの種類 4.35b6
, デフォルトのフォーマッタを表示 4.35
の価値を 4.35
, のりかもしれないけど、私がParseExceptionが、ユーザが入力する 無効 値とします。
こちらはコードしていました。
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
final JFormattedTextField ftf = new JFormattedTextField(nf);
ftf.setValue(new BigDecimal("1234.50"));
// Print the value from ftf
final JTextField txt = new JTextField(12);
txt.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
txt.setText(ftf.getValue().toString());
}
});
どのように同じ値としてユーザーを見ているのか?
解決
あなたはむしろNumberFormatter
よりNumberFormat
を拡張し、それが文字列が解析されたときに元の値を取り戻すことを確認するようにstringToValue
をオーバーライドする必要があります:
class StrictNumberFormatter extends javax.swing.text.NumberFormatter {
@Override
public Object stringToValue(String text) throws ParseException {
Object parsedValue = super.stringToValue(text);
String expectedText = super.valueToString(parsedValue);
if (! super.stringToValue(expectedText).equals(parsedValue)) {
throw new ParseException("Rounding occurred", 0);
}
return parsedValue;
}
public StrictNumberFormatter(NumberFormat nf) {
super(nf);
}
}
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
JFormattedTextField.AbstractFormatter formatter = new StrictNumberFormatter(nf);
final JFormattedTextField ftf = new JFormattedTextField(formatter);
ftf.setValue(new BigDecimal("1234.50"));
前と丸め後の値が一致しない場合は、このフォーマッタは、新しいテキストを拒否します。
注:これはの値のではなく、文字列を比較します。これは、グループ化文字("$1,000"
=> "$1000"
)を除去し、ゼロ("$1.20"
=> "$1.2"
)を末尾のような変更を許容します。 NumberFormat
が同じ値を返す場合、基本的に、それは許容されます。しかしNumberFormat
による制限は、まだ、例えば、適用されますあなたは、通貨記号を削除するか、先頭のスペースなどを入れない必要があります。
他のヒント
これを試してください:
txt.setText(ftf.getFormatter().valueToString(ftf.getValue()));
あなたはjava.text.ParseException
メソッドがスローvalueToString
を処理するためにも必要があります。
の編集を フォーマッタは役立つかもしれない、完全に無効なエントリを許可しないように設定することができます:
((DefaultFormatter)ftf.getFormatter()).setAllowsInvalid( false );