JavaFX组合框重复相同的值集

时间:2017-04-04 17:30:18

标签: javafx combobox repeat

我使用组合框从MySQL数据库中检索数据。但是当我将第一个值集插入数据库时​​,组合框值正在重复。我想知道它为什么会发生以及如何避免它。我在main上调用了这个方法。感谢

    public void FillCombo(){

    try{            
        String sql = "Select Name from Employee where Position='Driver'";
        pst = con.prepareStatement(sql);
        rs = pst.executeQuery();

        while(rs.next()){
            op.add(rs.getString("Name"));

        }
        selectDriverC.setItems(op);

        pst.close();
        rs.close();
    }
    catch(Exception e){
        System.out.println(e);
    }
}

1 个答案:

答案 0 :(得分:1)

添加一个条件,检查您要插入的字符串是否已在op中, 我假设op类型为ObservableList<String>。这应该有效:

public void FillCombo(){

    try{            
        String sql = "Select Name from Employee where Position='Driver'";
        pst = con.prepareStatement(sql);
        rs = pst.executeQuery();

        while(rs.next()){
            if(!op.contains(rs.getString("Name"))
            add(rs.getString("Name"));

        }
        selectDriverC.setItems(op);

        pst.close();
        rs.close();
    }
    catch(Exception e){
        System.out.println(e);
    }
}