Search code examples
javajcombobox

Populate JCombobox values depending on another JCombobox


I have two JComboboxes A and B, so if I select any item form A then values related to the item selected in A should fill in JCombobox B. I tried this but get an error:

java.lang.ArrayIndexOutOfBoundsException: 0

at pst.setString(1, client.getSelectedItem().toString());

try
{
    String query="select `User_Name` from Client where `Client_Name`='?' ";
    PreparedStatement pst=conn.prepareStatement(query);
    pst.setString(1, client.getSelectedItem().toString());

    ResultSet rs=pst.executeQuery();

    user.addItem("--Select--");
    while(rs.next())
    {
        user.addItem(rs.getString("User_Name"));            
    }
//      return;
    System.out.println(query);

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

Solution

  • The PresparedStatement takes care of quoting the parameter, when you use setString()

    Try

    String query="select User_Name from Client where Client_Name = ?";
    PreparedStatement pst=conn.prepareStatement(query); 
    pst.setString(1, String.valueOf(client.getSelectedItem()));
    

    I guess that when you use '?' the prepared statement does not count this as parameter and this is why you get the IndexOutOfBounce