How to add an object to a JComboBox in Java
In this tutorial, we are going to see how to add an object to a JComboBox in Java. JComboBox is part of the Java Swing package. JComboBox inherits from the JComponent class. JComboBox displays a contextual menu which shows a list and the user can select an option in this specified list.
Generally, JComboBox can contain elements of any type. If the type of the elements is an object, toString() method of the object will be used to get the name of the elements in the ComboBox. Here is an example that creates a ComboBox with elements of type “Person”:
How to add an object to a JComboBox in Java
import javax.swing.*;
public class Main
{
public static void main(String argv[]) throws Exception
{
// Create and add objects to the comboBox
JComboBox<Person> cb = new JComboBox<Person>(
new Person[]
{
new Person("Thomas", 25),
new Person("Emily", 18),
new Person("Alex", 33)
}
);
// Add Listener to the comboBox
cb.addActionListener(e -> {
JComboBox<Person> c = (JComboBox<Person>) e.getSource();
// Show selected item
Person p = (Person)c.getSelectedItem();
System.out.println(p.getName());
});
// create a frame
JFrame frame = new JFrame();
// add the comboBox to the frame
frame.add(cb);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Person
{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
Output:





