下面是KeyAdapter,我试图只接受小于65535的值。看起来好像它实际上应该有一个击键。例如,如果我输入" 55",System.out.println将产生" 5",做" 3298"将产生" 329"等
// Allows for unsigned short values only
KeyAdapter unsignedShortAdapter = new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
int tempInt = 0;
JTextField temp = null;
if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
getToolkit().beep();
e.consume();
}
try {
temp = (JTextField) e.getSource();
System.out.println(temp.getText());
tempInt = (Integer.parseInt(temp.getText().toString()));
} catch (NumberFormatException e1) {
} finally {
if (tempInt > (Short.MAX_VALUE * 2)) {
getToolkit().beep();
e.consume();
temp.setText(temp.getText().substring(0, temp.getText().length() - 1));
invalidate();
}
}
}
};
答案 0 :(得分:5)
因此,代替您找到的KeyListener
不可靠并且会导致许多令人讨厌的副作用(以及可能的文档变异例外:P),我们应该使用DocumentFilter
,因为它是为
public class ShortFilter extends DocumentFilter {
protected boolean valid(String text) {
boolean valid = true;
for (char check : text.toCharArray()) {
if (!Character.isDigit(check)) {
valid = false;
break;
}
}
if (valid) {
int iValue = Integer.parseInt(text);
valid = iValue <= (Short.MAX_VALUE * 2);
}
return valid;
}
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.insert(offset, text);
if (valid(sb.toString())) {
super.insertString(fb, offset, text, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (length > 0) {
StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.delete(offset, length);
sb.insert(offset, text);
if (valid(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
}
} else {
insertString(fb, offset, text, attrs);
}
}
}
您需要将其应用于字段的文档
((AbstractDocument) field.getDocument()).setDocumentFilter(new ShortFilter());
我看看
了解更多信息
包含十进制内容的更新
基本上,如果你想允许包含小数,你需要允许valid
方法中的字符。
您还需要检查当前文档的内容
StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
// Update the StringBuilder as per noraml
// Check valid as per normal
if (text.contains(".") && sb.contains(".")) {
// already have decimal place
} else {
// Business as usual...
}