這是UserController.java類。我無法從JavaFX中的數據庫加載用戶名combobox
public ObservableList<UserModelItem> options = FXCollections.observableArrayList();
@FXML
private ComboBox<UserModelItem> combo;
This is the UserModelItem.java.class
public static class UserModelItem{
private final SimpleStringProperty username;
public UserModelItem(String user){
super();
this.username = new SimpleStringProperty(user);
}
public String getUsername() {
return username.get();
}
public void setUsername(String uname){
username2.set(uname);
}
}
這是UserController.java.class
initialize方法public void initialize(URL location, ResourceBundle resources) {
combo.setItems(options);
}
這此FXML參照ComboBox-
<ComboBox fx:id="combo" layoutX="131.0" layoutY="377.0" onAction="#fillComboBox" prefWidth="150.0" />
這fillComboBox()函數被分配給組合框與fx:id組合通過SceneBuilder以及UserController類。
public void fillComboBox(ActionEvent event){
try{
Connection connect = SqLiteConnection.Connector();
String query = "select username from employee";
PreparedStatement ps = connect.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while(rs.next()){
options.add(new UserModelItem(rs.getString("username")));
}
ps.close();
rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
這是轉換ObservableList到與字符串
combo.setConverter(new StringConverter<UserModelItem>() {
@Override
public String toString(UserModelItem object) {
return object.getUsername();
}
@Override
public UserModelItem fromString(String string) {
// TODO Auto-generated method stub
return null;
}
});
}
我檢查了大部分的答案在計算器的功能,我的代碼是相同的還是那些我不能填充組合框。
請編輯您的問題,幷包含您的FXML文件中引用'fillComboBox'的元素。 – VGR
@VGR我已將FXML引用添加到組合框。請檢查 –