选择新项目时,Swing JComboBox 获取上一个项目

Swing JComboBox get previous item when new item selected

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

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);

        }
    });

假设 selected 的对象是 Paul,而我 select 在 John 之后。所以这里 actionPerfomed 被触发并且 comboBox.getSelectedItem(); 将 return 我们 John。我的问题是有什么办法可以拦截Paul之前吗?

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

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

资源:JComboBoxComponent