How to get the value that was written in editable JComboBox?

I continue to search, and it seems that everyone uses only JComboBox#getSelectedItem . But my combo box is editable , and the user can enter something . The getSelectedItem method returns one of the actual elements in the combo box, not the string entered in the field.

image description

If my field contains “Bar” and “Subject” and the user enters “Foo”, I want to get “Foo”!

Why getSelectedItem does not work

It was pointed out that getSelectedItem also returns the entered string. However, it was not noted 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 these 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.

+7
java jcombobox
source share
2 answers

Thus: combobox.getEditor().getItem() . Nice drawing.

+8
source share

Maybe something is wrong in the way you use getSelectedItem . This seems very good to me:

 JComboBox<String> combo = new JComboBox<>(new String[] {"bar", "item"}); combo.setEditable(true); JButton button = new JButton("Get"); button.addActionListener((ActionEvent e) -> { System.out.println(combo.getSelectedItem()); }); JFrame frame = new JFrame(); frame.setLayout(new FlowLayout()); frame.getContentPane().add(combo); frame.getContentPane().add(button); frame.pack(); frame.setVisible(true); 

If you press the button after selecting one of the predefined elements, it will print this element, and if you enter some text and then press the button, it will print this text.

+1
source share

All Articles