This discussion is archived
3 Replies Latest reply: Aug 12, 2012 11:52 PM by 954838 RSS

JComboBox.getSelectedItem when there are no other focusable components

954838 Newbie
Currently Being Moderated
Hi,

I have got a problem by getting the entered value of a JcomboBox when there are no other focusable components.
Is there a way to get the input text from a JComboBox which is editable without having other focusable components?

Here is a test case:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ComboTest extends JFrame
{
  public static void main( String[] args )
  {
    ComboTest frame = new ComboTest();
    frame.setVisible( true );
  }

  public ComboTest()
  {
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    setSize( 450, 300 );
    setLocationRelativeTo( null );
    JPanel contentPane = new JPanel();
    setContentPane( contentPane );

    final JComboBox combo = new JComboBox( new String[] { "Enter some text here and press Ok" } );
    combo.setEditable( true );
    contentPane.add( combo );
    JButton button = new JButton( " Ok " );
    button.setFocusable( false );
    contentPane.add( button );

    button.addActionListener( new ActionListener()
    {
      @Override
      public void actionPerformed( ActionEvent e )
      {
        System.out.println( combo.getSelectedItem() );
      }
    } );
  }
}
Just run the example and try to enter some text in the combobox. Hit the ok button to print the selectteditem (text) from the combobox to the console.
This always prints the first (and only) item from the combobox. When I disable the line 'button.setFocusable( false );' it works. But in my real application we don't want the button can get the focus.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points