Java – How to set textfield value based on combobox options in Java

comboboxjavajtextfieldswing

I've a table in database named customer that have attribute like code and name. I've called the value of the customer in other table and displayed it using combo-box. I've displayed the code in combo-box, and all I wanna do is when I choose the code in combo-box, value 'name' can be displayed in text-field , the 'name' appear based on code.

here is my code :

try {
        Connections con = new Connections();
        con.setConnections();
        String sql = "select * from customer";
        Statement stat = con.conn.createStatement();
        ResultSet rs=stat.executeQuery(sql);        
        while (rs.next()){
        cmb_custCode.addItem(rs.getString("custCode"));

        txt_custName.setText(rs.getString("custName")); // i'm confused in here, how can i call the name based on the code 
        }
}

 catch(Exception e){
    e.printStackTrace();
  }
 }

for example :

when the code 'B0001' is selected in the combobox, the Jtextfield must also display "Bob" , because code B0001 is belongs to Bob.

Best Answer

EDIT:

Ok. So let's say that you have a user Bob and his code is B001.

ItemStateChanged Method

...
String code = (String) cmb.getSelectedItem();
try{

String sql = "SELECT * FROM customer WHERE code='"+code"'"
PreparedStatement prst = con.prepareStatement();
ResultSet rs = prst.executeQuery(sql);
String name = "";

while(rs.next()){

name = rs.getString('name');
}
txt.setText(name);
}catch(Exception ex){
}

You shouldn't actually connect inside the itemStateChanged but this is just an example.