此示例演示ItemListener侦听JComboBox组件中所选项目的更改。
package org.nhooo.example.swing; import javax.swing.*; import javax.swing.border.BevelBorder; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.*; public class ComboBoxSelectionChange extends JFrame { public ComboBoxSelectionChange() { initialize(); } private void initialize() { setSize(300, 300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.LEFT)); String[] items = new String[] {"A", "B", "C", "D", "E", "F"}; JComboBox<String> comboBox = new JComboBox<>(items); final JTextArea textArea = new JTextArea(5, 15); textArea.setBorder(new BevelBorder(BevelBorder.LOWERED)); // 用于收听组合框中所选项目的更改 // 我们需要向组合框组件添加一个ItemListener,如图所示 // 下面。 comboBox.addItemListener(new ItemListener() { // 侦听是否已选择组合框的新项目。 public void itemStateChanged(ItemEvent event) { JComboBox comboBox = (JComboBox) event.getSource(); // 受事件影响的项目。 Object item = event.getItem(); textArea.setText("Affected items: " + item.toString()); if (event.getStateChange() == ItemEvent.SELECTED) { textArea.setText(item.toString() + " selected."); } if (event.getStateChange() == ItemEvent.DESELECTED) { textArea.setText(item.toString() + " deselected."); } } }); getContentPane().add(comboBox); getContentPane().add(textArea); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ComboBoxSelectionChange().setVisible(true); } }); } }