gpt4 book ai didi

java - 我想从两个 ComboBox 中选择 NAME 和 FILM 并将所选项目放入 H2 DB 中

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:03 25 4
gpt4 key购买 nike

我从 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 将仅显示 namelname

关于java - 我想从两个 ComboBox 中选择 NAME 和 FILM 并将所选项目放入 H2 DB 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55511788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com