我有一个名为 Client 的表,其中包含 clientID 和 clientName 作为字段,我想在组合框中显示这两个字段,但我只想在单击添加按钮后将 clientID 插入到我的另一个表中。
我有这个方法来填充我的组合框
private void fillClient(){
Connection con = getConnection();
String sql = "Select clientID, clientfname from client";
try {
pst=con.prepareStatement(sql);
optset = pst.executeQuery();
while (optset.next()){
String id = optset.getString("clientID");
String nme = optset.getString("clientfname");
String cmb = (id+"-"+nme);
clientCmb.addItem(cmb);
}
} catch (SQLException ex) {
Logger.getLogger(Reservation.class.getName()).log(Level.SEVERE, null, ex);
}}
问题是,插入的数据是组合字符串。
这是我将所选项目插入数据库的方法。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = getConnection();
String client = (String) clientCmb.getSelectedItem();
String driver = (String) driverCmb.getSelectedItem();
String van = (String) vanCmb.getSelectedItem();
String sql = "Insert into reservation (clientID,van,driverID) values('"+client+"','"+driver+"','"+van+"')";
try {
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
JOptionPane.showMessageDialog(this, "Saved");
} catch (SQLException ex) {
Logger.getLogger(Reservation.class.getName()).log(Level.SEVERE, null, ex);
}
}
创建一个代表您的客户的模型类并重写toString
:
public class Client {
private int id;
private String firstName;
private String lastName;
// Getters and setters
public String toString() {
return firstName + " " + lastName;
}
}
组合框项目中的文本将根据toString
方法显示。将此模型类设置为您的JComboBox
.
JComboBox<Client> comboBox = new JComboBox<>();
选择组合框项目后,您现在可以获得整个对象。对那个对象做任何你想做的事情。获取 id、name 或其他任何内容。
PS 如果所有这些代码都是由 NetBeans GUI 生成器生成的,我表示哀悼。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句