我正在尝试使用此静态方法重写我的 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]
所选项目返回值为:Teacher
不知道该怎么办。我希望它返回 3,这是老师的 ID。
完整项目位于:此链接
谢谢你。
我使用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())+",";
}