我想从数据库ID添加组合框索引.public static void selectCompany(javax.swing.JComboBox cmbCategory ){cmbCategory.removeAllItems();String sql=SELECT * FROM company_details;try{Connection conn=dbConnecti...

我想从数据库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);
}
}
cmbCategory是组合框对象.我想将组合框索引和组合框列表显示为类别名称.数据库是mysql.
解决方法:
您可以将对象添加到ComboBox,而不仅仅是字符串,所以这样的事情应该可以解决问题:
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和名称!).
织梦狗教程
本文标题为:如何在java中将数据库ID添加为组合框索引?


基础教程推荐
猜你喜欢
- Java实现FTP上传到服务器 2023-05-08
- 使用Spring中的scope配置和@scope注解 2023-01-02
- SpringBoot Session接口验证实现流程详解 2023-05-18
- 使用Mybatis-Plus时的SqlSessionFactory问题及处理 2023-08-07
- java中的HashMap多层嵌套 2023-06-01
- java中关于深拷贝的几种方式总结 2023-04-17
- EasyExcel工具读取Excel空数据行问题的解决办法 2023-04-06
- 在Java中使用MySQL排序规则 2023-10-30
- Spring Boot整合 NoSQL 数据库 Redis详解 2023-05-18
- jsp+Servlet编程实现验证码的方法 2023-08-03