2016-11-02 101 views
0

美好的一天我對編碼完全陌生。我正在構建一個除了其他庫項目之外還使用組合框的應用程序。我面臨的問題是,在嘗試從Mysql Db填充組合框項目時,每次單擊下拉菜單時項目值都會被複制。來自mysql的JavaFx組合框

我該如何防止這種情況發生?我明白我的方法本身可能是錯誤的。

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

} 
+0

也許你可以嘗試清除項目,然後再添加更多。但我不確定,如果你確實想要查詢每一次點擊,這似乎是一個微小的矯枉過正。 –

+0

你如何使用'getStation'方法? '@ FXML'(儘管公共方法沒有必要)看起來可能表明你將它用作fxml文件中的事件處理程序。請添加有關此方法如何用於問題的信息。 – fabian

+0

感謝您的回覆。@ el_chupacabra您的觀察是正確的,我並不想每次點擊都要查詢,我只希望在用戶點擊組合框按鈕時顯示項目,然後在列表中重置或清除項目關閉了。 Fabian是的@FXML使用是一個新手的錯誤,該方法被稱爲鼠標點擊。 –

回答

0

行,所以我移動的功能,以在控制器的initialize()方法和創建的被叫站

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

} 

一個Observabale列表,然後在原有的功能只留下這一行....似乎在工作。

@FXML 
private void getStation() { 

    comboBoxStation.setItems(stationsList); 
}