Search code examples
javacomboboxitemlistener

how to handle 2 different combobox itemListener in same itemlistener function?


I Have two ComboBoxes

JcomboBox1.addItemListener(this)
jComboBox2.addItemListener(this)

How can I handle these in the same itemListener Function?
I am handling it for 1 combobox but need to handle with both combo box

public void itemStateChanged(ItemEvent ie) {
       String Product=(String)jComboBox1.getSelectedItem();
          ResultSet rs=db.GetPriceOfaProduct(Product);
          try{
              rs.next();
              int price=rs.getInt("pPrice");
             jLabel6.setText("Amount Per Item is "+price);
          }catch(Exception e)
          {
              System.out.println("Error in Taking Product Price");
          }

Solution

  • Use ItemEvent.getSource() to check which JComboBox has changed selection.

    Please be aware on changing selection, the item listener will be notified twice, once on the item deselected, followed by another on the item selected.

    public static void main(String[] args) {
        JFrame frame = new JFrame("test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(500, 500));
        frame.getContentPane().setLayout(new GridLayout(5, 5));
        JComboBox<String> comboBox1 = new JComboBox<>(new String[] { "11", "12" });
        JComboBox<String> comboBox2 = new JComboBox<>(new String[] { "21", "22" });
        ItemListener listener = (e) -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                if (e.getSource() == comboBox1) {
                    System.out.printf("JComboBox 1 state changed: %s selected\n", e.getItem());
                }
                else if (e.getSource() == comboBox2) {
                    System.out.printf("JComboBox 2 state changed: %s selected\n", e.getItem());
                }
            }
        };
        comboBox1.addItemListener(listener);
        comboBox2.addItemListener(listener);
        frame.getContentPane().add(comboBox1);
        frame.getContentPane().add(comboBox2);
        frame.setVisible(true);
    }