- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we 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
- Related Articles
- How can we implement an editable JLabel in Java?\n
- How can we implement auto-complete JComboBox in Java?\n
- Can we disable JComboBox arrow button in Java?
- How can we set the border to JComboBox items in Java?
- How can we sort the items of a JComboBox in Java?
- How can we implement a JToggleButton in Java?
- How can we implement transparent JDialog in Java?
- How can we set the foreground and background color to JComboBox items in Java?
- How can we implement a Custom HashSet in Java?
- How can we implement a scrollable JPanel in Java?
- How can we implement a rounded JTextField in Java?
- How can we implement a timer thread in Java?
- How can we implement a custom iterable in Java?
- How can we implement the SubmissionPublisher class in Java 9?
- How can we implement the Subscriber interface in Java 9?

Advertisements