Java Jcombobox Class Example : Page 2 of 2

EDITABLE JCOMBOBOX

Java Swing Tutorial Explaining the Editable JComboBox Component. JComboBox is like a drop down box —
you can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, when
the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists.

EDITABLE JCOMBOBOX SOURCE CODE

JComboBox’s getSelectedItem() is used to get what is entered into the control. However when a user types something into the JCombBox rather than selecting an item from the list and does not hit “enter” after entering the text, the getSelectedItem() does not return what is currently entered in the field (it instead gets the last selected item). The users often do not know to hit enter when they change the value in the JComboBox so they just click an “OK” button on the panel (signifying a save) and the value in the JComboBox is not properly saved. But the below program overcomes this probelm by simulating an enter key in the JComboBox or get the value that has been manually entered when the user does not hot “enter” in the JComboBox.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBoxEditable extends JFrame
{
	JComboBox jcmbNames;

	public JComboBoxEditable()
	{
		String[] names = { "hemanth", "Shawn", "Hunter", "Undertaker", "Big Show" };

		jcmbNames = new JComboBox( names );
		jcmbNames.setEditable( true );
		getContentPane().add(jcmbNames, BorderLayout.NORTH);

		JButton jbnOk = new JButton("Ok");
		getContentPane().add(jbnOk, BorderLayout.SOUTH);

//		Print Name of the Selected Combo Box Item to Console when OK button is pressed
		jbnOk.addActionListener( new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				System.out.println( jcmbNames.getSelectedItem() );
			}
		});

//		Print Name of the Selected Combo Box Item to Console when Enter is pressed

		jcmbNames.addActionListener( new ActionListener()
				{ public void actionPerformed(ActionEvent e)
				  { System.out.println( jcmbNames.getSelectedItem() );
				  }
				});
	}

	public static void main(String[] args)
	{
		JComboBoxEditable frame = new JComboBoxEditable();
		frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
		frame.pack();
		frame.setLocationRelativeTo( null );
		frame.setVisible( true );
	 }
}

Output

Download Editable JComboBox Source Code

Like us on Facebook