IllegalStateExceptionを回避し、JTextFieldが「通知で変更を試みる」ことを許可する、つまり、リスナーがトリガーされた場合に独自のテキストを設定するために使用できる魔法があるかどうか疑問に思いました。
参考までに、JTextFieldでのユーザーの入力に応じて、12個の列挙型の範囲で最も可能性の高い一致を返すオートコンプリート関数をプログラムしようとしています。
これがコードサンプルです。列挙型の結果をきしむ私の不器用なアルゴリズムを許さなければなりません。コメントで例外を生成するコードを強調表示しました:
jtfElement1.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
String s = jtfElement1.getText();
int[] attributes = new int[13];
// iterate through each enum
for (BaseEnumAttributes b: BaseEnumAttributes.values()) {
// iterate through the length of the current text in jtfElement1
for (int i = 0; i < s.length(); i++) {
if (s.length() <= b.toString().length()) {
if (b.toString().charAt(i) == s.charAt(i)) {
// increase the number of "hits" noted for that enum
attributes[b.ordinal()] = attributes[b.ordinal()] + 1;
}
}
}
}
int priorC = 0;
int rightC = 0;
// iterate through the "array" of enums to find the highest score
for (int j = 0; j < attributes.length; j++) {
if (attributes[j] > priorC) {
priorC = attributes[j];
rightC = j;
}
}
if (!s.equals("")) {
// assign to b the Enum corresponding to the "array" with highest score
BaseEnumAttributes b = BaseEnumAttributes.values()[rightC];
iController.updateInputElement1String(b.toString());
// THIS TRIGGERS EXCEPTION
jtfElement1.setText(b.toString());
}
}
});