我的jcombobox已经有了这个:
myjcombobox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!(Character.isDigit(c)
|| (c == KeyEvent.VK_BACK_SPACE)
|| (c == KeyEvent.VK_DELETE))) {
getToolkit().beep();
e.consume();
}
}
});
此代码可防止在数字之外写入jcombobox中的任何字符。只有DIGITS。但由于我的jcombobox是可编辑的,用户可以写几个数字,这就是问题,我想设置最大长度4位但不知道我该怎么办....
提前致谢
答案 0 :(得分:1)
将自己的Document
设置为组件(假设它是JTextField
):
.setModel(new PlainDocument(){
public void insertString(int offset, String text, AttributeSet attr){
if(getLength() + text.length() > 4){
Toolkit.getToolkit.beep();
return;
}
for(char c : text.toCharArray(){
if(!Character.isDigit(c){
|| (c != KeyEvent.VK_BACK_SPACE)
|| (c != KeyEvent.VK_DELETE)){
Toolkit.getToolkit.beep();
return;
}
}
super.insertString(offset,text,attr);
}
});
答案 1 :(得分:1)
假设你的JCombobox是最终的,你可以试试这个:
myjcombobox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (myjcombobox.getEditor().getItem().toString().length() < 4) {
if (!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) {
f.getToolkit().beep();
e.consume();
}
} else {
e.consume();
}
}
});