0

I am writing Bing/Google instant search kind of feature in combo box, so this combo box provides suggestions to the user based on what he has typed. The program works like a charm but their is one bug that I am unable to figure out how to solve. The problem is, the first character typed is recognised once the second the character has been typed, same goes for other position of characters too.

Here is the code:

public MyClass extends JFrame
{
 private  Document doc;
public MyCode()
{
  comboxBox= new JComboBox();
  Handler handle = new Handler();
  JTextComponent comp = (JTextComponent) comboBox.getEditor().getEditorComponent();
  doc = comp.getDocument().addDocumentListener(handle);
  comboBox.addKeyListener(handle);
}

private class Handler implements DocumentListener,KeyListener
{
    String dataTobeSearched= "";
    @Override
    public void changedUpdate(DocumentEvent event) {
        try
        {
            dataTobeSearched = doc.getText(0, doc.getLength());
            System.out.println("Data to be searched "+dataTobeSearched);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
 }

    @Override
    public void keyPressed(KeyEvent event) {

            changedUpdate(null);
    }
}

What am I doing wrong?

I added the keyListener to the combobox editor because the DocumentListener wasn't getting invoked when something was being typed in the combobox? If there is an other easy alternative to this, then please share it.

How can I solve the above stated problem?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
James Aflred
  • 87
  • 2
  • 5
  • 12

2 Answers2

3

Wrap the call inside changedUpdate() in SwingUtilities.invokeLater()

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • It ensures that GUI classes are created/updated on the EDT. See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details. – Andrew Thompson Feb 05 '13 at 12:08
  • During event processing the length could reflect wrong value because event processing is in progress. TO call your code after change reflected in the Document use the call. – StanislavL Feb 05 '13 at 12:09
  • ok. Why doesn't document listener work when something is changed in combobox editor. Why is it dependent on another event listener? – James Aflred Feb 05 '13 at 12:21
  • It;s hard to say what's wrong and which effect you expect. Post SSCCE and describe expected and actual behaviour as well as steps to reproduce. – StanislavL Feb 05 '13 at 12:33
1

According to the Java tutorial on Oracle website, changedUpdate() method will not work for plain text documents. If this is your case, use insertUpdate() and/or removeUpdate().

The recommendation of using SwingUtilities inside the method is still valid.

Ram
  • 3,092
  • 10
  • 40
  • 56
hfontanez
  • 5,774
  • 2
  • 25
  • 37