我的问题与这个问题类似,但对我不起作用=(
我有一个数据库命名的客户id,名称,电话和电子邮件。当我注册一个客户时,他的名字和id会显示在Jlist上。现在,我想点击Jlist中的名称,并"搜索"该客户的所有数据(id、姓名、电话和电子邮件)。我已经有了链接数据的textField,但不起作用。。。
我做了什么:
DefaultListModel model = new DefaultListModel();
client_listClientes.setModel(model);
try {
String host = "jdbc:derby://localhost:1527/ANAIA_DB";
String uName = "*****";
String uPass = "*****";
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement();
String sql = "SELECT * FROM APP.CLIENTS";
int id_col = rs.getInt("clientID"); // I need to make this work.. when i select a value, it gives me the id for that client
ResultSet RS = stmt.executeQuery("SELECT * FROM APP.CLIENTS WHERE CLIENTID='"+id_col+"'");
rs = stmt.executeQuery(sql);
while (RS.next()){
String name = rs.getString("clientName");
client_textName.setText(name);
String phone = rs.getString("clientPhone");
client_textPhone.setText(phone);
String email = rs.getString("clientMail");
client_textMail.setText(email);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(main.this, err.getMessage());
}
我读到我必须使用监听器,但我尝试了另一个问题中的示例,但没有成功=/
只需一次将所有数据加载到Client
对象中,而不是每次都试图返回并访问数据库。
class Client {
int id;
String name;
String phone;
String email;
// getter and setters
@Override
public String toString() {
return id + " : " + name;
}
}
然后,您可以将所有数据加载到客户端对象中,并将它们添加到模型中
ResultSet RS = stmt.executeQuery("SELECT * FROM APP.CLIENTS");
...
while (RS.next()){
Client client = new Client();
client.setId(rs.getInt("id");
client.setName(rs.getString("clientName"));
client.setPhone(rs.getString("clientPhone"));
client.setEmail(rs.getString("clientMail");
model.addElement(client);
}
然后单击JList,只需提取所选的Client
对象,并使用getters
设置文本字段
client_listClientes.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
JList list = (JList)e.getSource();
Client client = (Client)list.getSelectedValue();
textfield.setText(client.getEmail());
}
}
});