public class ComboItem
{
private int index;
private String name;
public ComboItem(int pindex, String pName)
{
this.index = pindex;
this.name = pName;
}
public int GetIndex()
{
return this.index;
}
public String GetName()
{
return this.name;
}
public void SetIndex(int pindex)
{
this.index = pindex;
}
public void SetName(String pName)
{
this.name = pName;
}
主要课程
private void FillNameComboBox(JComboBox combo) throws IOException{
try{
combo.removeAllItems();
Connect c =new Connect();
Statement stmnt= c.MakeConnection().createStatement();
ResultSet rset=stmnt.executeQuery("select idCostumer,Name from Costumer");
while(rset.next()){
int index=Integer.parseInt(rset.getString("idCostumer"));
String name=rset.getString("Name");
ComboItem ci=new ComboItem(index, name);
combo.addItem(ci);
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(NameComboBox, e);
}
}
每当我运行应用程序时,它一直给我的索引而不是ID ...我该怎么做?screen shot
答案 0 :(得分:1)
1-首先创建一个Compo框类,让它命名为" ComboItem"并执行以下操作:
公共类ComboItem {
private int index;
private String name;
private String col;
public ComboItem(int pindex, String pName) {
this.index = pindex;
this.name = pName;
}
public ComboItem(int pindex, String pcol, String pName) {
this.index = pindex;
this.col = pcol;
this.name = pName;
}
public int GetIndex() {
return this.index;
}
public String GetName() {
return this.name;
}
public String GetCol() {
return this.col;
}
public int SetIndex(int pindex) {
this.index = pindex;
return pindex;
}
public String SetName(String pName) {
this.name = pName;
return pName;
}
public String SetCol(String pCol) {
this.col = pCol;
return pCol;
}
// This will be used internally by JComboBox as the label to be displayed.
@Override
public String toString() {
return name;
}
// to get the Index of Combobox depends on ComboItem Class
public static int getIndexById(JComboBox combo, int id) {
for (int i = 1; i < combo.getItemCount(); i++) {
try {
ComboItem c = (ComboItem) combo.getItemAt(i);
int tempId = c.GetIndex();
if (tempId == id) {
return i;
}
} catch (Exception e) {
}
}
return 0;
}
}
之后,您将能够在其他类中设置和获取compo box Items,如下所示:
设置项目ID和名称
try
{
combo.removeAllItems();
conn = Operations.SqlConnector();
String sql = "select EmpID, EmpName from Emp";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
ComboItem nullValue = new ComboItem(0,"- select -");
combo.addItem(nullValue);
while(rs.next())
{
int index = Integer.parseInt(rs.getString("EmpID"));
String name = rs.getString("EmpName");
ComboItem c = new ComboItem(index,name);
combo.addItem(c);
c.GetName();
}
pst.close();
rs.close();
}
catch(SQLException | NumberFormatException e)
{
JOptionPane.showMessageDialog(null, e);
}
获取物品ID或名称
ComboItem dept = (ComboItem) ComboBox_DeptID.getSelectedItem();
int deptID = dept.GetIndex();
您还可以使用GetIndexByID(),如下所示:
int dept = ComboItem.getIndexById(ComboBox_DeptID, BindList().get(index).GetDeptID());
ComboBox_DeptID.setSelectedIndex(dept);
最好的问候。