javaswingjcombobox

Swing JComboBox get previous item when new item selected


I'm a beginner in swing I have the following code :

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

        }
    });

Suppose the object that is selected is Paul and I select after John. So here actionPerfomed is triggered and the comboBox.getSelectedItem(); will return us John. My question is there any way to intercept Paul before ?


Solution

  • Use the addItemListener to check if any item has been selected

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

    Resource: JComboBoxComponent