jcombobox持续加载数据

时间:2014-02-02 18:48:28

标签: java swing jcombobox

根据我的说法,我已经创建了小型登录jframe。我在jpasswordField焦点增益上调用了事件。现在当光标进入jpasswordfield时,它会填充来自数据库的值。第二次当光标进入jpasswordfield时,它再次加载值。它应该只加载一次值。

private void jPasswordField1FocusGained(java.awt.event.FocusEvent evt) {

    un = jTextField2.getText();
    try{
        con = DriverManager.getConnection(path,"root","ashu");
        stat = con.createStatement();
        ResultSet rs = stat.executeQuery("SELECT * FROM login where username = '"+un+"'");
        while(rs.next()){
            if(rs.getString("username").equals(un)){
                jComboBox1.addItem(rs.getString("company"));
            }
        }
        rs.close();
        stat.close();
        con.close();
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(this, "Database problem !", 
                                             "Error", 
                                              JOptionPane.ERROR_MESSAGE);
    }
}

1 个答案:

答案 0 :(得分:0)

每次jPasswordField1获得焦点时,都会调用此方法 你必须使用某种布尔条件才能获取一次你的值。 这是一个样本:

boolean check = true; // line 1
private void jPasswordField1FocusGained(java.awt.event.FocusEvent evt) {
if (check){ // line 2
un = jTextField2.getText();
try{
    con = DriverManager.getConnection(path,"root","ashu");
    stat = con.createStatement();
    ResultSet rs = stat.executeQuery("SELECT * FROM login where username = '"+un+"'");
    while(rs.next()){
        if(rs.getString("username").equals(un)){
            jComboBox1.addItem(rs.getString("company"));
        }
    }
    rs.close();
    stat.close();
    con.close();
}
catch(Exception e){
    JOptionPane.showMessageDialog(this, "Database problem !", 
                                         "Error", 
                                          JOptionPane.ERROR_MESSAGE);
   }
  } // line 3

    check=false; // line 4
}

刚刚在代码中添加了布尔逻辑(4行) 这只会在获得焦点时仅从数据库中获取一次值 之后,布尔检查变为false 如果您觉得这个答案有帮助,请接受吗?感谢