问题
I'm doing a search on the database using an editable JComboBox, but when it comes to writing, only accepts write me a letter and any amount of numbers, how I can do that allows me to write letters and numbers?
The following code accepts only numbers, backspace key, enter key, but not letters.
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);
}
}
}
});
回答1:
Here is a JComboBox
which allows users to enter only (English) letters and numbers and the _
character:
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);
}
});
}
}
}
The idea is to set a new editor for the combo box and add a document filter to its text field.
来源:https://stackoverflow.com/questions/34371647/can-not-write-editable-jcombobox