How to set JComboBox not to select an element when created? (Java)

Posted by Alex Cheng on Stack Overflow See other posts from Stack Overflow or by Alex Cheng
Published on 2010-05-04T04:26:02Z Indexed on 2010/05/04 4:38 UTC
Read the original article Hit count: 217

Filed under:
|
|

Hi all.

Problem:

I am using JComboBox, and tried using setSelectionIndex(-1) in my code (this code is placed in caretInvoke())

suggestionComboBox.removeAllItems();
    for (int i = 0; i < suggestions.length; i++) {
        suggestionComboBox.addItem(suggestions[i]);
    }
    suggestionComboBox.setSelectedIndex(-1);
    suggestionComboBox.setEnabled(true);

This is the initial setting when it was added to a pane:

    suggestionComboBox = new JComboBox();
    suggestionComboBox.setEditable(false);
    suggestionComboBox.setPreferredSize(new Dimension(25, 25));
    suggestionComboBox.addActionListener(new SuggestionComboBoxListener());

When the caretInvoke triggers the ComboBox initialisation, even before the user selects an element, the actionPerformed is already triggered (I tried a JOptionPane here): First popup (notice that "flow byte_jump" is selected): alt text

Second popup (I think the setSelectionIndex is executed) alt text

Then in the end: alt text

The problem is: My program autoinserts the selected text when the user selects an element from the ComboBox. So without the user selecting anything, it is automatically inserted already.

How can I overcome the problem in this situation? Thanks.

© Stack Overflow or respective owner

Related posts about java

Related posts about jcombobox