Search code examples
javaswingjdbcjtextfieldjcombobox

fill jcombobox from database depending on text from textfield


I want to fill the jComboBox with values from database. and these values depend on the text written in the textfield. eg: if I write a in the texfield, the combobox will have all values starting with a. The values are from a databse

Here's my code:

private void FillCombo(){
String url = "jdbc:mysql://localhost:3306/pharmacy";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "test";
String sql = "select medicinename from medicine where medicinename like '%"+jTextField5.getText()+"%'"; 

try{

    Class.forName(driver).newInstance();
    System.out.println("1");
    Connection con = (Connection)DriverManager.getConnection(url,user,pass);
    System.out.println("Connected");
    Statement st=(Statement) con.createStatement();        
    PreparedStatement pst = con.prepareStatement(sql);
    ResultSet rs = pst.executeQuery();
    while(rs.next()){
    String name = rs.getString("medicinename");
    jComboBox1.addItem(name);

    }

} catch(Exception e){
JOptionPane.showMessageDialog(null, e);    

}}

Solution

  • I want not just one caracter eg: if i write a, as, asp it fill aspirine myproblem is that the combobox is already filled. want it empty when i start.

    Simply use JComboBox#removeAllItems() to removes all items from the item list on each stroke of any key in the JTextField.

    Points to Remember