Editable JComboBox
Editable JComboBox Source Code
Oct 30, 2006 by Hemanth
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
GO TO PAGE 1 -> JComboBox