根据文本字段中的文本从数据库中填充jcombobox

时间:2014-05-24 08:40:22

标签: java swing jdbc jtextfield jcombobox

我想用数据库中的值填充jComboBox。这些值取决于文本字段中写入的文本。 例如:如果我在texfield中写一个,那么组合框将包含以a开头的所有值。值来自数据库

这是我的代码:

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);    

}}

1 个答案:

答案 0 :(得分:1)

  

我想要的不仅仅是一个例子:如果我写一个,as,asp它填充aspirine myproblem就是组合框已经填满了。我开始时想把它弄空。

只需使用JComboBox#removeAllItems()即可删除JTextField中任意键的每个笔划中项目列表中的所有项目。

要记住的要点