我试图使用这个静态方法覆盖我的JComboBox getSelectedItem方法:
public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
// query to select ID and TITLE from profiles table
String query = "SELECT ID,TITRE FROM " + tableName + ";";
ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
ArrayList visualItems = new ArrayList(); // the Items of my combobox [item1,item2]
ArrayList idItems = new ArrayList(); // the corresponding IDs for each item [id1,id2]
while (myJComboResultSet.next()) {
visualItems.add(myJComboResultSet.getObject("TITRE")); // filling items set
idItems.add(myJComboResultSet.getObject("ID")); // filling IDs set
}
System.out.println("IDItems=" + idItems); // checking that my Items are filled
System.out.println("visualItems=" + visualItems); // checking that my IDs are filled
// creating a combobox of previous items
jComboBox = new JComboBox(visualItems.toArray()) {
ArrayList values = idItems;
// overriding the getSelectedItem to return the corresponding selected item's ID
@Override
public Object getSelectedItem() {
Object get = values.get(super.getSelectedIndex());
System.out.println("get = " + get);
return get;
}
};
}
我从另一个框架调用此方法:
JComboBoxTools.setupID_TITLE_ComboBox(J_Users_Profile,"profiles");
但是在执行时它不起作用。 输出:
visualItems = [管理员,教师,学生]
IDItems = [0,3,5]
所选项目的返回值为:教师
不知道该怎么办我希望它返回3,这是教师的身份。
完整项目位于:this link
谢谢。答案 0 :(得分:0)
我使用mapComboBoxModel获取所需的值
public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
String query = "SELECT ID,TITRE FROM " + tableName + ";";
ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
HashMap myMap = new HashMap();
while (myJComboResultSet.next()) {
myMap.put(myJComboResultSet.getObject("TITRE"), myJComboResultSet.getObject("ID"));
}
jComboBox.setModel(new MapComboBoxModel(myMap) {
@Override
public Object getValue(Object selectedItem) {
return map_data.get(selectedItem); //To change body of generated methods, choose Tools | Templates.
}
});
}
我重写了getValue以返回ID。
if (myComponent instanceof JComboBox) {
JComboBox jComboBox = (JComboBox) myComponent;
MapComboBoxModel model = (MapComboBoxModel) jComboBox.getModel();
values+=""+model.getValue(model.getSelectedItem())+",";
}