
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Editable JComboBox in Java
JComboBox
- A JComboBox can extend JComponent class and it is a combination of a text field and a drop-down list from which the user can choose a value.
- If the text field portion of the control is editable, the user can enter a value in the field or edit a value retrieved from the drop-down list.
- By default, the user not allowed to edit the data in the text field portion of the JComboBox. If we want to allow the user to edit the text field, call setEditable(true) method.
- A JComboBox can generate an ActionListener, ChangeListener or ItemListener when the user actions on a combo box.
- A getSelectedItem() method can be used to get the selected or entered item from a JComboBox.
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JEditableComboBoxTest extends JFrame { public JEditableComboBoxTest() { setTitle("JEditableComboBox Test"); setLayout(new BorderLayout()); final JComboBox combobox = new JComboBox(); final JList list = new JList(new DefaultListModel()); add(BorderLayout.NORTH, combobox); add(BorderLayout.CENTER, list); combobox.setEditable(true); combobox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if (ie.getStateChange() == ItemEvent.SELECTED) { ((DefaultListModel) list.getModel()).addElement(combobox.getSelectedItem()); combobox.insertItemAt(combobox.getSelectedItem(), 0); } } }); setSize(new Dimension(375, 250)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) throws Exception { new JEditableComboBoxTest(); } }
Output
Advertisements