Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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:

Advertisements
