有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

mysql如何在java中添加数据库id作为组合框索引?

我想从数据库id添加组合框索引

 public static void selectCompany(javax.swing.JComboBox cmbCategory ){
    cmbCategory.removeAllItems();
    String sql="SELECT * FROM company_details";
    try{
        Connection conn=dbConnection();
        PreparedStatement pstmt=conn.prepareStatement(sql);
        ResultSet rs=pstmt.executeQuery(sql);
        while(rs.next()){
            int id=rs.getInt("company_id");
            String category=rs.getString("company_name");
            cmbCategory.addItem(id);
            cmbCategory.addItem(category);
        }
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

CMB类别是组合框对象。我想将id显示为组合框索引,组合框列表显示为类别名称。数据库是mysql


共 (3) 个答案

  1. # 1 楼答案

    您可以向组合框中添加对象,而不仅仅是字符串,因此类似这样的操作应该可以做到:

        while(rs.next()){
            int id=rs.getInt("company_id");
            String category=rs.getString("company_name");
            Object[] itemData = new Object[] {id, category};
            cmbCategory.addItem(itemData);
        }
    

    正如Harry Joy指出的,您可以通过使用ListCellRenderer来告诉swing这个元素应该如何呈现:

    class MyListRenderer extends JLabel implements ListCellRenderer {
    
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Object[] itemData = (Object[])value;
            setText((String)itemData[1]);
    
            return this;
        }
    }
    

    您可以稍后将其分配给JComboBox:

    cmbCategory.setRenderer(new MyListRenderer());
    

    这样做的明显优点是,ID和类别名称都位于一个对象中,因此当用户在组合框中选择一个项目时,您可以访问该对象的所有属性(ID和名称!)

  2. # 2 楼答案

    如果您想将公司id设置为combobox项目索引,那么我的答案是您不能设置项目索引。如果要同时显示id和类别,请连接id和公司名称

    cmbCategory.addItem(id + " " + category);
    
  3. # 3 楼答案

    使用自定义渲染器时,您将无法通过键盘输入项目的第一个字符来访问组合框项目。这是因为combobox模型的搜索使用每个项的toString()方法来首先搜索请求的项。在本例中,数组的toString()实现不是meaningul

    另一种解决方案是创建自定义对象并重写对象的toString()方法,如本例所示:How to use Map element as text of a JComboBox