Combobox 如何创建可以绑定到单独POJO上的字段的JavaFX8组合框
在以下情况下,我很难找到任何线索。假设我有一个名为DatabaseRecord的记录,它是一个包含多个字段的POJO:Combobox 如何创建可以绑定到单独POJO上的字段的JavaFX8组合框,combobox,lambda,java-8,javafx-8,Combobox,Lambda,Java 8,Javafx 8,在以下情况下,我很难找到任何线索。假设我有一个名为DatabaseRecord的记录,它是一个包含多个字段的POJO: public class DatabaseRecord { private Long recordId; private StringProperty foreignKeyId; private StringProperty otherValuesForMainRecord.... ... setters/getters public cla
public class DatabaseRecord {
private Long recordId;
private StringProperty foreignKeyId;
private StringProperty otherValuesForMainRecord....
... setters/getters
public class LookUpDataValue {
private String recordId;
private String descriptiveText;
private String otherValues.....
....
我有一个组合框,显示foreignKeyId值的可选值,如下所示:
@FXML
ComboBox<LookUpDataValue> combobox;
combobox.setCellFactory
(new Callback<ListView<LookUpDataValue>, ListCell<LookUpDataValue>>() {
@Override
public ListCell<LookUpDataValue> call(ListView<LookUpDataValue> p) {
ListCell<LookUpDataValue> cell = new ListCell<LookUpDataValue>() {
@Override
protected void updateItem(LookUpDataValue item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText("");
} else {
setText(item.getDescriptiveText());
}
}
};
return cell;
}
});
@FXML
组合框组合框;
combobox.setCellFactory
(新回调(){
@凌驾
公共ListCell调用(ListView p){
ListCell=新ListCell(){
@凌驾
受保护的void updateItem(lookUpdateAvalue项,布尔值为空){
super.updateItem(项,空);
if(空){
setText(“”);
}否则{
setText(item.getDescriptiveText());
}
}
};
返回单元;
}
});
我想将POJO DatabaseRecord.foreignKeyIdProperty双向绑定到combobox.valueProperty()-但这不起作用,因为一个是字符串,另一个是LookUpdateAvalue对象
我希望在加载记录时正确设置此组合框,并在更改记录时反过来更新该组合框
如果有人能给我指点,我将不胜感激……我无法更改我的数据模型,因此我找到了以下有效的解决方案
// Handle ComboBox event.
myComboBox.setOnAction((event) -> {
LookUpDataValue selected = myComboBox.getSelectionModel().getSelectedItem();
if(selected != null){
dto.setForeignKeyId(selected.getId());
}
});
这很有效。感谢您的评论。这里建模数据的通常方法是使用
DatabaseRecord
创建一个类型为lookUpdateAvalue
(或者在JavaFX世界中为ObjectProperty
)的字段,而不是存储外键。(外键本质上是数据存储方式的一个实现细节,而不是数据本身的一个功能。)然后在从数据库加载时让数据库访问代码填充该字段(或者只使用ORM框架,它将自动管理该字段)。如果您以这种方式设计OO模型,那么绑定就很简单了。你有机会像那样重构吗?我现在不确定。我的遗留系统很旧。有些DTO是这样制定的,其他的则不是这样。我来看看,看看这在这儿行不行。