Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value that has been written in editable JComboBox?

Tags:

java

jcombobox

I keep searching and it seems like everybody is using only the JComboBox#getSelectedItem. But my combo box is editable and the user can enter anything. The getSelectedItem method returns one of the actual items in the combo box, not a string entered in the field.

image description

If my box contains "Bar" and "Item" and user enters "Foo", I want to get "Foo"!

Why getSelectedItem does not work

It was pointed out that getSelectedItem does also return the string entered. It was not pointed out though, that this only works after the user stops editing the field. I attached these event listeners:

Component[] comps = input.getComponents();
//Third is the text field component
comps[2].addKeyListener(new KeyListener() {
  public void keyTyped(KeyEvent e) {
    doSomething();
  }
});
//Also fire event after user leaves the field
input.addActionListener (new ActionListener () {
    @Override
    public void actionPerformed(ActionEvent e) {
      doSomething();
    }
});

And this were the results:

KeyEvent:
 JComboBox.getEditor().getItem() = 6  
 JComboBox.getSelectedItem()     = null
KeyEvent:
 JComboBox.getEditor().getItem() = 66
 JComboBox.getSelectedItem()     = null
KeyEvent:
 JComboBox.getEditor().getItem() = 666
 JComboBox.getSelectedItem()     = null
ActionEvent:
 JComboBox.getEditor().getItem() = 6666
 JComboBox.getSelectedItem()     = 6666

As you can see, the action event listener could capture the value, but the key event could not.

like image 705
Tomáš Zato - Reinstate Monica Avatar asked Mar 17 '15 16:03

Tomáš Zato - Reinstate Monica


People also ask

What happens when a user clicks on a JComboBox?

A JComboBox is a compact mechanism for selecting from a small number of options. The options are displayed when the user clicks on the combo box. If it is made editable the user can also enter text that is not supplied as one of the options.

How do I make JComboBox not editable?

u can make ur jcombobox uneditable by calling its setEnabled(false). A JComboBox is unEditable by default. You can make it editable with the setEditable(boolean) command. If you are talking about enabled or disabled you can set that by the setEnabled(boolean) method.


1 Answers

This way: combobox.getEditor().getItem(). Nice drawing.

like image 134
uraimo Avatar answered Nov 14 '22 06:11

uraimo