Search code examples
javaswingtextactionlistenerjcombobox

Highlight text in JComboBox then erase it if user input something


I'm trying to make a 'JComboBox' that can take user input, but that's not the problem. I want that if the 'JComboBox' loose the focus then regain it the text is highlighted. Then if the user input anything it erase the text in place and replace it by the new input.

I have read this but it's not what i want to do. I only want to highlight the text not the whole thing.

Here is my guess : *Not the actual code for it is a logic problem

Step 1 - I will need either a FocusListener or a MouseListener

public class ComboEvent implements MouseListener {
    @Override
    public void onMouseClick(MouseEvent e) {
        highLightText();
    }
}

Step 2 - That's the rough part, i really don't know how to do it...

Step 3 - Then erase the text when something is typed. There again I'm not quite sure how to perfectly achieve this.

public class EraserEvent implements KeyListener {

    @Override
    public void keyPressed(KeyEvent e) {
        char t = (char) e.getSource();
        //I know that there is know setText function in a JComboBox
        comboBox.setText("t");  
    }
}

Solution

  • You need to add the logic to the editor of the combo box which happens to be a text field.

    The basic code would be something like:

        ComboBoxEditor editor = comboBox.getEditor();
        JTextField textField = (JTextField)editor.getEditorComponent();
        textField.addFocusListener( new FocusListener()
        {
            public void focusGained(final FocusEvent e)
            {
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {
                        JTextField textField = (JTextField)e.getSource();
                        textField.selectAll();
                    }
                });
            }
    
            public void focusLost(FocusEvent e) {}
        });