使用值来激活Jcombobox actionlistener而不是getselectedindex?

时间:2013-05-04 13:21:12

标签: java swing jdbc jcombobox

这里是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任何帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

使用getSelectedItem()获取对当前所选ComboItem的引用,并id;使用getSelectedIndex()获取它的索引。

由于setSelectedIndex()会触发组合的ActionListener,导航控件(如⊲PrevNext⊳按钮)可以委托给组合,如图所示here

  • index获取getSelectedIndex()

  • 递增或递减index

  • index

  • 执行范围检查
  • 通过setSelectedIndex(index)将选择权委派给组合。

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

for (int i = 0; i < dcbm.getSize(); i++) {
    ComboItem item = (ComboItem) dcbm.getElementAt(i);
    // check item
}