我正在使用可编辑的JComboBox在数据库中搜索,但是当涉及到写作时,我只接受给我写一封信和任何数量的数字,我怎样才能写字母和数字呢?
以下代码只接受数字、后退键、输入键,但不接受字母。
comboBusqueda.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
String cadenaEscrita = comboBusqueda.getEditor().getItem().toString();
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
if(comparar(cadenaEscrita)){
buscar(cadenaEscrita);
}else{
buscar(comboBusqueda.getSelectedItem().toString());
comboBusqueda.getSelectedItem();
}
}
if (evt.getKeyCode() >= 65 && evt.getKeyCode() <= 90
|| evt.getKeyCode() >= 96 && evt.getKeyCode() <= 105
|| evt.getKeyCode() == 8
|| evt.getKeyCode() == KeyEvent.VK_ENTER
) {
comboBusqueda.setModel(dc.getLista(cadenaEscrita));
if (comboBusqueda.getItemCount() > 0) {
comboBusqueda.getEditor().setItem(cadenaEscrita);
comboBusqueda.showPopup();
} else {
comboBusqueda.addItem(cadenaEscrita);
}
}
}
});发布于 2015-12-19 15:27:59
这是一个JComboBox,允许用户只输入(英文)字母和数字以及_字符:
public class ComboBoxExample extends JPanel {
ComboBoxExample() {
JComboBox<String> cb = new JComboBox<>();
cb.setEditable(true);
cb.setEditor(new FilterCBEditor());
add(cb);
}
class FilterCBEditor extends BasicComboBoxEditor {
FilterCBEditor() {
((AbstractDocument) editor.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if (string.matches("\\w+"))
super.insertString(fb, offset, string, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (text.matches("\\w+"))
super.replace(fb, offset, length, text, attrs);
}
});
}
}
}其思想是为组合框设置一个新的编辑器,并在其文本字段中添加一个文档筛选器。
https://stackoverflow.com/questions/34371647
复制相似问题