在Java/Swing中,是否有一种方法可以合法地“试图在通知中进行突变”?
-
02-10-2019 - |
题
我想知道我是否可以使用某种魔法来绕过违法的exception,并让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());
}
}
});
解决方案
使用文档过滤器或自定义文档,您可能会更好。
期望其他听众在事件派遣期间查看该文档是否保持不变?
其他提示
使用swingutilities.invokelater()放置所有修改
也许您可以在careTupDate()终止后使用线程延迟setText()。
我在同一问题上发现了一个简单的解决方案:
if(false)u'r将文本设置为jtextfield时,将caretupdate()锁定为布尔值(false)。 。这样的事情:
boolean caret = true;
私有void listValueChanged(javax.swing.event.listselectionevent evt){caret = false; name.setText((字符串)list.getSelectedValue()); caret = true; }
private void nameCaretUpdate(javax.swing.event.CaretEvent evt) {
if(caret){
model = new DefaultListModel();
this.fillList(name.getText());
list.setModel(model);
}
}
创建自定义文档并覆盖InsertString()
filenameText = new JTextField(new FilenameDocument(), "", 0);
...
/**
* document which adds .xml extension if not specified
*
*/
private class FilenameDocument extends PlainDocument {
@Override
public void insertString(int offset, String insertedText, AttributeSet set)
throws BadLocationException {
if (offset == 0) {
insertedText = insertedText.trim( );
}
super.insertString(offset, insertedText, set);
if (filenameText != null) {
final int caretPos = filenameText.getCaretPosition();
String text = filenameText.getText().trim();
if (text.indexOf('.') == -1) {
filenameText.setText(text + ".xml");
filenameText.setCaretPosition(caretPos);
}
}
}
}
请注意,调用setText将导致对InsertString()的递归调用,因此请确保您有停止条件。
我很惊讶没有人回答这个问题,但是您不会更好地实施可编辑 JSPINNER 与 SpinnerListModel?
不隶属于 StackOverflow