我从 h2 db 中填写了两个组合框。在组合框中你只能看到名称。我怎样才能从组合框中获取所选项目的 ID?并通过id来写入新的executeQuery
JComboBox<String> comboBox = new JComboBox<>();
try {
String sql="SELECT clientid,name,lastname FROM client";
conn = DBConnector.getConnection();
state = conn.prepareStatement(sql);
result = state.executeQuery();
while(result.next()) {
String name = result.getString("name");
String lname = result.getString("lastname");
comboBox.addItem(name+" "+lname);
}
} catch (Exception e) {
e.printStackTrace();
}
comboBox.setBounds(10, 91, 146, 22);
contentPane.add(comboBox);
JComboBox<String> comboBox_1 = new JComboBox<>();
try {
String sql="SELECT title,yearpub FROM films";
conn = DBConnector.getConnection();
state = conn.prepareStatement(sql);
result = state.executeQuery();
while(result.next()) {
String name = result.getString("title");
String year = result.getString("yearpub");
comboBox_1.addItem(name+" "+year);
}
} catch (Exception e) {
e.printStackTrace();
}
comboBox_1.setBounds(194, 91, 146, 22);
contentPane.add(comboBox_1);
您仅将名字和姓氏添加到您发布的这行代码中的第一个 JComboBox
中:
comboBox.addItem(name+" "+lname);
ID 未存储在 JComboBox
模型中,因此不在所选项目中。
默认情况下,JComboBox
显示其模型中对象的方法 toString()
返回的 String
,因此一个简单的解决方案是创建自定义类和自定义 toString()
方法。例如,对于第一个 JComboBox
:
public class Client {
private int id;
private String name;
private String lname;
public Client(int id, String name, String lname) {
this.id = id;
this.name = name;
this.lname = lname;
}
public int getId() {
return id;
}
public String toString() {
return name + " " + lname;
}
}
然后您创建并填充一个 JComboBox
,如下所示:
JComboBox<Client> comboBox = new JComboBox<>();
try {
String sql="SELECT clientid,name,lastname FROM client";
conn = DBConnector.getConnection();
state = conn.prepareStatement(sql);
result = state.executeQuery();
while(result.next()) {
int id = result.getInt("clientid");
String name = result.getString("name");
String lname = result.getString("lastname");
comboBox.addItem(new Client(id, name, lname));
}
} catch (Exception e) {
e.printStackTrace();
}
现在,当您调用 JComboBox
中的 getSelectedItem()
方法时,它将返回一个包含 ID 的 Client
对象。
Object obj = comboBox.getSelectedItem();
Client client = (Client) obj;
int id = client.getId();
请注意,Client
类的 toString()
方法意味着 JComboBox
将仅显示 name
和 lname
。
我是一名优秀的程序员,十分优秀!