JavaFx:双向绑定,TableView中的选定值(JavaFx: Bidirectional Binding, selected value in TableView)

编程入门 行业动态 更新时间:2024-10-28 06:23:42
JavaFx:双向绑定,TableView中的选定值(JavaFx: Bidirectional Binding, selected value in TableView)

我需要一些帮助,我试图将模型中对象的属性与一些标签和文本字段绑定。

label1.textProperty().bind(myModel.getSelectedObject().getNameProperty());

在这种情况下, getSelectedObject()是TableView中的选定对象。 不知怎的,这不能按预期工作。 当模型的值发生变化时,标签不会改变。

我使用Bindings帮助类进行了修复以修复此问题:

label1.textProperty().bind(Bindings.select(myModel.getSelectedObject(), "name"));

只有使用Bindings帮助类,标签的文本才能正确绑定到对象的name-property。

现在我试图通过双向绑定获得相同的结果。 任何想法?

如果我像这样绑定它,它没有任何效果(与第一个代码剪切相同)

textField.textProperty().bindBidirectional(myModel.getSelectedObject().getNameProperty());

I need some help, im trying to bind properties of an object in my model with some labels and textfields.

label1.textProperty().bind(myModel.getSelectedObject().getNameProperty());

in this case getSelectedObject() is the selected Object in a TableView. Somehow this doesn't work as expected. When the model's value changes, the label doesn't change.

I mangaged to fix this issue with the Bindings help class:

label1.textProperty().bind(Bindings.select(myModel.getSelectedObject(), "name"));

Only with the Bindings help class the label's text gets binded correctly to the name-property of the object.

now im trying to get the same result with a bidirectional binding. Anyone any ideas?

If i bind it like this, it has no effect (same as first code-snipped)

textField.textProperty().bindBidirectional(myModel.getSelectedObject().getNameProperty());

最满意答案

SelectionModel ChangeListener启用切换绑定。 试试看。

tableView.getSelectionModel().selectedItemProperty().addListener((o, ov, nv) -> { if (ov != null) textField.textProperty().unbindBidirectional(ov.nameProperty()); if (nv != null) { textField.setDisable(false); textField.textProperty().bindBidirectional(nv.nameProperty()); } else { textField.setDisable(true); textField.setText(""); } });

注意:

如果从TableView的项目中删除了选定的项目,则使用删除的项目作为oldValue而不是null来调用此ChangeListner 。 因此无需关心删除列表项。

ChangeListener for SelectionModel enable to switch binding. Try it out.

tableView.getSelectionModel().selectedItemProperty().addListener((o, ov, nv) -> { if (ov != null) textField.textProperty().unbindBidirectional(ov.nameProperty()); if (nv != null) { textField.setDisable(false); textField.textProperty().bindBidirectional(nv.nameProperty()); } else { textField.setDisable(true); textField.setText(""); } });

NOTE:

In case selected item is removed from TableView's items, This ChangeListner is called with removed item as oldValue rather than null. So no needs to care removal of list item .

更多推荐

本文发布于:2023-07-20 05:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1194823.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   双向   JavaFx   TableView   selected

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!