我的代码遇到了问题,我想不通。
我要做的是用sqllite中的数据填充jcombobox,然后获取所选项目的索引,以便我可以将其用于进一步的活动。我正在使用数组列表填充jcombobox。
下面是数组列表的代码:
public ArrayList<Battery> batteries() throws Exception {
ArrayList<Battery> batteriesList = new ArrayList();
try {
Statement stmt = null;
Connection conn = null;
Battery currentBattery = null;
String url = "jdbc:sqlite:batteries.db";
conn = DriverManager.getConnection(url);
String sql = "Select * from batteries";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
currentBattery = new Battery(rs.getString("companyName"), rs.getString("batteryType"), rs.getFloat("batteryVolt"), rs.getFloat("batteryAmp"));
batteriesList.add(currentBattery);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
return batteriesList;
}
下面是我填充jcombobox的代码:
public void showBatteries() {
ArrayList<Battery> list = null;
try {
list = batteries();
for (int i = 0; i < list.size(); i++) {
jComboBox_BatteryChooser.addItem(list.get(i).getCompanyName() + " " + list.get(i).getBatteryModel());
}
} catch (Exception ex) {
Logger.getLogger(mainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
要获取所选项目的索引,我使用以下方法:
public void fillData(){
System.out.println("Index of item: "+jComboBox_BatteryChooser.getSelectedIndex());
}
但是,函数filldata()的结果始终为0。你能给我指出正确的方向或帮我解决这个问题吗?非常感谢:)
暂无答案!
目前还没有任何答案,快来回答吧!