JCombobox Listener如何在选择项目时启用它? [英] JCombobox Listener how to enable it when item is selected?

查看:66
本文介绍了JCombobox Listener如何在选择项目时启用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个显示名称来自数据库的JComboBox Patients_Details

I have a JComboBox that displays Name From database 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);
    }
}

这是来自comboitem类,只返回名称和不是id

This is from comboitem class that only returns the name and not the id

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

我的问题是如何获取选定项目以便执行此操作我不知道如何做到这一点我已经尝试了大约2个小时的所有代码
任何帮助将不胜感激

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

NB我是Java初学者

NB I am Java beginner

  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 时,您可以查找所选值并调用您需要的方法。

Simply add an ActionListener to the combo box. When actionPerformed is called, you can look up the selected value and call what ever methods you need to.

For示例:

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

看看......

  • How to write action listeners
  • How to use combo boxes

详情

这篇关于JCombobox Listener如何在选择项目时启用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆