简体   繁体   English

JCombobox Listener 如何在选择项目时启用它?

[英]JCombobox Listener how to enable it when item is selected?

I have a JComboBox that displays Name From database Patients_Details我有一个 JComboBox 显示数据库中的名称Patients_Details

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

This is from comboitem class that only returns the name and not the id这是来自仅返回名称而不返回 id 的组合项类

  public String toString() {
    return this.name  ;
   }

My question is how do I get the selecteditem so that this action can be performed I have no clue how to do this I have been trying all bunch of code for almost 2 hours any help will be much appreciated我的问题是如何获取所选项目以便可以执行此操作我不知道如何执行此操作我已经尝试了近 2 个小时的所有代码,任何帮助将不胜感激

NB I am Java beginner NB我是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 ); 
  }
}  

Simply add an ActionListener to the combo box.只需将ActionListener添加到组合框即可。 When actionPerformed is called, you can look up the selected value and call what ever methods you need to.actionPerformed被调用时,您可以查找选定的值并调用您需要的任何方法。

For example:例如:

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

Have a look at ...看一下 ...

For more details更多细节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM