In this tutorials, I am going to show you how to use Java JComboBox. Java ComboBox is a swing component that combines drop down with editable field.
Java JComboBox :
JComboBoxDemo.java
package com.onlinetutorialspoint.swing;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.activation.MailcapCommandMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JComboBoxDemo extends JFrame {
private JComboBox comboBox;
private JLabel label;
private static final String[] names = {
"bulb1",
"bulb2",
"bulb3"};
private Icon[] icons = {
new ImageIcon("C:\\images\\bulb1.gif"),
new ImageIcon("C:\\images\\bulb2.gif"),
new ImageIcon("C:\\images\\bulb3.gif") };
JComboBoxDemo() {
super("JCombobox Demo");
setLayout(new FlowLayout());
comboBox = new JComboBox(names);
comboBox.setMaximumRowCount(3);
comboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
label.setIcon(icons[comboBox.getSelectedIndex()]);
}
}
});
add(comboBox);
label = new JLabel(icons[0]);
add(label);
}
public static void main(String[] args) {
JComboBoxDemo jComboBoxDemo = new JComboBoxDemo();
jComboBoxDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jComboBoxDemo.setSize(350, 150);
jComboBoxDemo.setVisible(true);
}
}
Output :
Changing the Items :
Editable JComboBox :
We can make the JComboBox as editable by using setEditable(true) like below.
Enable Editing
comboBox.setEditable(true);
Output :
Happy Learning 🙂