我在項目中使用了JavaFX,Hibernate,Spring。JavaFX組合框沒有顯示對象的正確值
我需要用我的對象值填充組合框。 在我的組合框中,我只需要顯示模型中的標題值。
我的模型類:
public class Sector extends Identifier {
private String title;
private List<Stage> stageList;
public List<Stage> getStageList() {
return stageList;
}
public void setStageList(List<Stage> stageList) {
this.stageList = stageList;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Sector{" +
"id='" + getId() + '\'' +
"title='" + title + '\'' +
", stageList=" + stageList +
'}';
}
}
和
public class Stage extends Identifier {
private String name;
private Station firstStation;
private Station secondStation;
private List<CommunicationDistance> communicationDistanceList;
public Stage() {
}
public Stage(String name, Station firstStation, Station secondStation) {
this.name = name;
this.firstStation = firstStation;
this.secondStation = secondStation;
}
public List<CommunicationDistance> getCommunicationDistanceList() {
return communicationDistanceList;
}
public void setCommunicationDistanceList(List<CommunicationDistance> communicationDistanceList) {
this.communicationDistanceList = communicationDistanceList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Station getFirstStation() {
return firstStation;
}
public void setFirstStation(Station firstStation) {
this.firstStation = firstStation;
}
public Station getSecondStation() {
return secondStation;
}
public void setSecondStation(Station secondStation) {
this.secondStation = secondStation;
}
@Override
public String toString() {
return "Stage{" +
"id='" + getId() + '\'' +
"name='" + name + '\'' +
", firstStation=" + firstStation +
", secondStation=" + secondStation +
", communicationDistanceList=" + communicationDistanceList +
'}';
}
在我的控制器有一些方法偵聽的組合框做一些其他的操作與此數據: (約電池廠我讀來自this question,還有from here)
@FXML
public void currentSectorSelected(ActionEvent actionEvent) {
ObservableList<Stage> observableList = FXCollections.observableArrayList(((Sector) sector.getSelectionModel().getSelectedItem()).getStageList());
stage.setItems(observableList);
stage.getSelectionModel().selectFirst();
stage.setCellFactory(new Callback<ListView<Stage>, ListCell<Stage>>() {
@Override
public ListCell<Stage> call(ListView<Stage> param) {
return new ListCell<Stage>(){
@Override
public void updateItem(Stage item, boolean empty){
super.updateItem(item, empty);
if(!empty) {
setText(item.getName());
setGraphic(null);
} else {
setText(null);
}
}
};
}
});
}
這是我正確的對象,但是,我仍然無法理解如何格式化我的組合框從我的部門和其他對象只顯示標題字段? 你能展示一些有效/正確的例子來格式化我的組合框輸出嗎?
編輯1: 在我的init方法中,我只是將我的對象列表添加到組合框。我不知道這是正確的做法,但如果我想選擇組合框的值後,以驗證該數據 - 我必須設置一個完整的對象在組合框中:
你調試過嗎? setText(item.getName()); 這裏返回一個字符串,組合框只顯示該字符串,這意味着問題不在您的組合框中,但「getName()」返回錯誤的值 - >模型可能設置不正確。 – DVarga
嗨DVarga。請看看我的新編輯。 –
你說得對。保存的數據存在問題,而不是組合框。隨着ItachiUchiha變體和你的建議 - 我已經解決了這個問題。謝謝! –