0

这是 Jcombobox 它有两个项目名称和 id

   public void ComboItem() {

chooser.removeAllItems();
chooser.addItem("Please Select...");
try {   

         String sql="select * from Patients_Details";
         pst = conn.prepareStatement(sql);
         rs=pst.executeQuery();

        while (rs.next()) {
            String id = rs.getString("Patient_ID"); // Get the Id
            String name = rs.getString("Name"); // Get the Name 

            ComboItem comboItem = new ComboItem(id, name); // Create a new ComboItem
            chooser.addItem(comboItem); // Put it into the ComboBox
            String tmp=comboItem.getid();
        }


    } catch (SQLException sqle) {
        System.out.println(sqle);
    }

Jcombobox ActionListener 代码

private void chooserPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {                                                     
    Object selectedValue = chooser.getSelectedIndex();

    try{


      String sql="select * from Patients_Details where Patient_ID=? ";
      pst=conn.prepareStatement(sql);
      pst.setObject(1, selectedValue);
      rs=pst.executeQuery();
      if(rs.next()){

      String add1=rs.getString("Patient_ID");
      txtpatientid.setText(add1);
      String add2=rs.getString("Name");
      txtname.setText(add2);
      String add3=rs.getString("Age");
      txtage.setText(add3);
      String add4=rs.getString("Gender");
      txtgender.setText(add4);
      String add7=rs.getString("Date");
      txtdate.setText(add7);

       }

  }

  catch(Exception e) {
    JOptionPane.showMessageDialog(null,e ); 
  }
}                     

我的问题是:如何使用 id 作为值来触发 JCombobox 侦听器而不是 getSelectedindex 任何帮助将不胜感激。

4

1 回答 1

1

用于getSelectedItem()获取对当前选中的 的引用ComboItem,它是id; 用于getSelectedIndex()获取它的索引。

因为setSelectedIndex()触发组合ActionListener,导航控件(例如⊲PrevNext⊳按钮)可以委托给组合,如下所示

  • index从获取getSelectedIndex()

  • 增加或减少index.

  • 对 执行范围检查index

  • 通过 将选择委托给组合setSelectedIndex(index)

的特定实现ComboBoxModel,例如DefaultComboBoxModel,可以使用迭代来搜索:

for (int i = 0; i < dcbm.getSize(); i++) {
    ComboItem item = (ComboItem) dcbm.getElementAt(i);
    // check item
}
于 2013-05-04T16:12:25.210 回答