首页 > 解决方案 > Swing JComboBox在选择新项目时获取上一个项目

问题描述

我是摇摆的初学者,我有以下代码:

String[] names = new String[]{
            "James", "Joshua", "Matt", "John", "Paul" };

    JComboBox comboBox = new JComboBox<String>(names);
    // Create an ActionListener for the JComboBox component.
    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            // Get the source of the component, which is our combo
            // box.
            JComboBox comboBox = (JComboBox) event.getSource();

            // Print the selected items and the action command.
            Object selected = comboBox.getSelectedItem();
            System.out.println("Selected Item  = " + selected);

        }
    });

假设选择的对象是 Paul,我在 John 之后选择。所以这里 actionPerfomed 被触发并且comboBox.getSelectedItem();会返回我们John。我的问题是之前有什么方法可以拦截Paul吗?

标签: javaswingjcombobox

解决方案


使用addItemListener检查是否已选择任何项目

comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    String selected = (String) event.getItem();
                    // add your logic
                }
            }
        });

资源:JComboBoxComponent


推荐阅读