Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top