来自mysql的JavaFx组合框

时间:2016-11-02 07:01:08

标签: mysql javafx combobox

美好的一天我对编码完全陌生。我正在构建一个除了其他库项目之外还使用组合框的应用程序。我面临的问题是,当尝试从Mysql Db填充组合框项目时,每次单击下拉列表时,项目值都会重复。

如何防止这种情况发生?我明白我的方法本身可能是错误的。

    @FXML
public void getStation() {
    String sqlStationName = " select * from station ";

    try {
        conn = (Connection) DBConnection.connect();
        PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
        ResultSet stnRS = pstStn.executeQuery(sqlStationName);

        while (stnRS.next()) {

        comboBoxStation.getItems().add(stnRS.getString("stationName"));


        }

        stnRS.close();
        pstStn.close();
        conn.close();

    } catch (SQLException ex) {
        System.err.println("ERR" + ex);
    }

}

1 个答案:

答案 0 :(得分:0)

好的,所以我将函数移动到控制器中的initialize()方法并创建了一个名为station的Observabale列表

     private ObservableList<String> stationsList = FXCollections.observableArrayList();

    @Override
public void initialize(URL url, ResourceBundle rb) {
    // 
    String sqlStationName = " select * from station ";

    try {
        conn = (Connection) DBConnection.connect();
        PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
        ResultSet stnRS = pstStn.executeQuery(sqlStationName);

        while (stnRS.next()) {

            stationsList.add(stnRS.getString("stationName"));

        }

        stnRS.close();
        pstStn.close();
        conn.close();

    } catch (SQLException ex) {
        System.err.println("ERR" + ex);
    }

}

然后在原始函数中只留下这一行....似乎正在工作。

    @FXML
private void getStation() {

    comboBoxStation.setItems(stationsList);
}
相关问题