Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JCombobox侦听器选择项时如何启用它?_Java_Swing_Jdbc_Actionlistener_Jcombobox - Fatal编程技术网

Java JCombobox侦听器选择项时如何启用它?

Java JCombobox侦听器选择项时如何启用它?,java,swing,jdbc,actionlistener,jcombobox,Java,Swing,Jdbc,Actionlistener,Jcombobox,我有一个JComboBox,它显示数据库中的名称和详细信息 public void ComboItem() { chooser.removeAllItems(); chooser.addItem("Please Select..."); try { String sql="select * from Patients_Details"; pst = conn.prepareStatement(sql); rs=pst.executeQ

我有一个JComboBox,它显示数据库中的名称和详细信息

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);
    }
}
这来自comboitem类,该类只返回名称而不返回id

  public String toString() {
    return this.name  ;
   }
我的问题是如何获取selecteditem以便执行此操作我不知道如何执行此操作我已经尝试了将近2个小时的所有代码 任何帮助都将不胜感激

注:我是Java初学者

  private void chooserPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {

    try{
      String sql="select * from Patients_Details where Patient_ID=? ";
      pst=conn.prepareStatement(sql);
      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 add5=rs.getString("Date");
      txtdate.setText(add5);
       }
  }
  catch(Exception e) {
    JOptionPane.showMessageDialog(null,e ); 
  }
}  

只需在组合框中添加一个
ActionListener
。调用
actionPerformed
时,您可以查找所选值并调用所需的任何方法

例如:

chooser.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        Object selectedValue = chooser.getSelectedValue();
        // carry on with what ever you need
    }
});
看看


有关更多详细信息

非常感谢,尽管我对
object selectedValue=chooser.getSelectedIndex()做了一些细微的更改