- 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 to add items in a JComboBox on runtime in Java
The following is an example to add items on runtime on a JComboBox in Java:
Example
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComboBox<String> combo = new JComboBox<>(new String[] { "One","Two", "Three","Four","Five", "Six" }); JButton add = new JButton("Add"); add.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { combo.addItem("New"); } }); frame.add(combo); frame.add(add, BorderLayout.NORTH); frame.setSize(500, 100); frame.setVisible(true); } }
Output
Now, we have the following items:
Now, click “Add” above to add a new item on runtime. After clicking, a new item would be visible in the bottom as shown in the following screenshot:
- Related Articles
- How to display the items in a JComboBox in Java
- How to center align the items of a JComboBox in Java?
- How to display the different font items inside a JComboBox in Java?
- How can we sort the items of a JComboBox in Java?
- How can we set the border to JComboBox items in Java?
- How can we set the foreground and background color to JComboBox items in Java?
- How to add items to an array in java dynamically?
- How to display the first element in a JComboBox in Java
- Java Program to disable the first item on a JComboBox
- How do I add multiple items to a Java ArrayList in single statement?
- How to hide and display JCombobox with a JCheckBox in Java?
- How to add items to a list in C#?
- How to handle action event for JComboBox in Java?
- How to handle the Runtime Exception in Java?
- Java Program to set JComboBox in JOptionPane

Advertisements