有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在同一个itemListener函数中处理2个不同的组合框itemListener?

我有两个组合框

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

如何在同一个itemListener函数中处理这些问题
我正在处理1个组合框,但需要处理两个组合框

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

共 (2) 个答案

  1. # 1 楼答案

    使用ItemEvent.getSource()检查哪些JComboBox更改了选择

    请注意更改选择时,项目侦听器将收到两次通知,一次是关于取消选择的项目,另一次是关于所选项目

    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);
    }
    
  2. # 2 楼答案

    您可以使用JComboBox comboBox = (JComboBox) ie.getItem();,而不是使用comboBox1.getSelectedItem()comboBox2.getSelectedItem(),这样您就可以引用触发事件的JComboBox


    使用getSource()而不是getItem()