Thursday, January 19, 2012

How can I access text entered in a JComboBox, when the user does not hit enter?

Location: http://www.jguru.com/faq/view.jsp?EID=53753 Author: Sandip Chitale Question originally asked by tracey marsh The easiest way to do this is to watch for changes in focus. WHen the user leaves the combo box (to press a button or work with another component, for example) you can catch a focusLost event from the JComboBox's editor. The following code assumes you haven't changed the editor for the combo box (which is probably the case).
if (comboBox.getEditor().getEditorComponent()
    instanceof JTextField) {
  JTextField tf = 
    (JTextField)comboBox.getEditor().getEditorComponent();

  tf.addFocusListener(new FocusAdapter() {
    public void focusLost(FocusEvent fe) {
      // get the text using getText() method
    }});
}