I have a JComboBox, once every second I want to retreive a set of strings from a database and set those strings to the contents of the JComboBox, and one of them as the currently selected value. But I also want the user to be able to edit the JComboBox and add a value to the database and set it as the current value.
I want to the be able to detect when characters are entered into the JComboBox, so I can reset a count down which prevents updating the JComboBox as long as it's not zero. My first instinct was to use a KeyListener but the Java tutorial on combo boxes says this,
Although JComboBox inherits methods to register listeners for low-level events — focus, key, and mouse events, for example — we recommend that you don't listen for low-level events on a combo box.
And they go on to say that the events fired may change depending on the look and feel.
This is a little dicey, but it should work to listen to the Document updates on the Editor component (A JTextField).
JComboBox cb = new JComboBox();
Component editor = cb.getEditor().getEditorComponent();
if (editor instanceof JTextField) {
((JTextField) editor).getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent documentEvent) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void changedUpdate(DocumentEvent documentEvent) {
//To change body of implemented methods use File | Settings | File Templates.
}
});
}
Those *Update(DocumentEvent documentEvent) methods should get called for every character typed/deleted from the JComboBox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With