JComboBox edit detection

I have a JComboBox, once a second I want to find a set of rows from the database and set these rows to the contents of the JComboBox, and one of them as the current selected value. But I also want the user to be able to edit the JComboBox and add the value to the database and set it as the current value.

I want to be able to detect when characters are entered in the JComboBox, so I can reset the countdown, which prevents the JComboBox from updating if it is non-zero. My first instinct was to use KeyListener, but the Java combo-block tutorial says this,

Although the JComboBox inherits listener registration methods for low-level events — such as focus, key, and mouse events — we recommend that you not listen to low-level events in a combo box.

And they continue to argue that fired events can change depending on the appearance.

+8
java swing jcombobox
source share
2 answers

This is a bit risky, but it should work to listen for document updates in 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 be called for each character typed / removed from the JComboBox.

+4
source share

I would like to add that the changedUpdate method will not trigger a notification for text documents. If you are using a text-based text component, you must use insertUpdate and / or removeUpdate.

Recently, I had to use a document listener as a way to disable / enable a button if the user edited the combo box. I did something like this and worked very well:

 public class MyDocumentListener implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { setChanged(); notifyObservers(true); } @Override public void removeUpdate(DocumentEvent e) { setChanged(); notifyObservers(false); } @Override public void changedUpdate(DocumentEvent e) { // Not used when document is plain text } } 

Then I added this listener to the combo box as follows:

 ((JTextComponent) combobox.getEditor().getEditorComponent()) .getDocument().addDocumentListener(new MyDocumentListener()); 

This works because the document associated with the combo box is plain text. When I used changeUpdate, I did not.

+2
source share

All Articles