This demo sends messages to the console.
A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items. A JComboBox can be editable or read-only.
Compare to JList
Reference: JComboBox vs JList
JComboBoxTest.java
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JComboBoxTest extends JFrame { JComboBoxTest() { setTitle("JComboBox Test"); String devices[] = {"Resistor","Voltage Source","Current Source","Ground"}; JComboBox<String> jcb = new JComboBox<String>(devices); //jcb.setEditable(true); //jcb.setSelectedIndex(3); jcb.addItemListener(itemEvent -> { if (itemEvent.getStateChange()==ItemEvent.SELECTED) { int ndx = jcb.getSelectedIndex(); setTitle(devices[ndx]); } System.out.println(itemEvent.paramString()); Object obj = itemEvent.getItem(); if (obj instanceof String) System.out.println("Object: " + obj); }); setLayout(new FlowLayout()); add(jcb); setSize(300, 250); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new JComboBoxTest(); } }
Maintained by John Loomis, updated Fri Apr 03 15:12:17 2020