gpt4 book ai didi

java - JTable:如何从绑定(bind)到数据源的表中获取选定对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:00:40 25 4
gpt4 key购买 nike

我有 JTable,其中“元素”属性绑定(bind)到对象列表,这是主表。还有详细信息表,其中“元素”属性绑定(bind)到主表中的 selectedElement。我是在 NetBeans GUI 构建器的帮助下完成的。现在我试着得到这样的东西:

SomeEntityType selectedObject= (SomeEntityType) masterTable.getSelectedElement ()

在源代码中,但在JTable 中没有这样的属性,只有“getSelectedRow”。那么,如何从绑定(bind)到源(对象列表)的 JTable 中获取选定对象?我读过类似的问题,但只找到 getValueAt(rowId,columnId) 方法的链接,但在我的任务中,选择哪一列并不重要,因为选择了整行。

最佳答案

不知道 Netbeans,只知道它使用了 Beansbinding 的一个版本,所以下面的肯定可以以某种方式应用

使用绑定(bind)框架的整个想法是您从不直接与 View 对话,而是完全专注于您的模型(或 bean):此类模型的某些属性绑定(bind)到某个属性一个 View ,你的代码只监听你的 bean 属性的变化。 “SelectedElement”是绑定(bind)的人工属性(实际上,是 JTableAdapterProvider 的,但这不是您需要知道的:-),因此将您的模型属性绑定(bind)到它 - 这是手动执行此操作的片段:

    // model/bean 
public class AlbumManagerModel .. {
// properties
ObservableList<Album> albums;
Album selectedAlbum;

// vents the list of elements
ObservableList<Album> getManagedAlbums() {
return albums;
}

// getter/setter
public Album getSelectedAlbum() {
return selectedAlbum;
}

public void setSelectedAlbum(Album album) {
Album old = getSelectedAlbum();
this.selectedAlbum = album;
firePropertyChange("selectedAlbum", old, getSelectedAlbum());
}


}

// bind the manager to a JTable

BindingGroup context = new BindingGroup();
// bind list selected element and elements to albumManagerModel
JTableBinding tableBinding = SwingBindings.createJTableBinding(
UpdateStrategy.READ,
albumManagerModel.getManagedAlbums(), albumTable);
context.addBinding(tableBinding);
// bind selection
context.addBinding(Bindings.createAutoBinding(UpdateStrategy.READ_WRITE,
albumManagerModel, BeanProperty.create("selectedAlbum"),
albumTable, BeanProperty.create("selectedElement_IGNORE_ADJUSTING")
));
// bind columns
tableBinding.addColumnBinding(BeanProperty.create("artist"));
...
context.bind();

关于java - JTable:如何从绑定(bind)到数据源的表中获取选定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7308834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com