JavaFX8:如何在Tableview中创建用于选择行的侦听器? [英] JavaFX8: How to create listener for selection of row in Tableview?

查看:998
本文介绍了JavaFX8:如何在Tableview中创建用于选择行的侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在一个屏幕上有两个tableview,这导致两个TableView都有用户可以选择的行。

I currently have two tableviews in one screen, which results in both TableViews have rows which the user can select.

现在我只想选择一行同时(从哪个TableView中选择它无关紧要)。我正在考虑某种类型的侦听器,当选择一行时,该侦听器会取消选择另一行。这是我的初始设置:

Now I want only one row to be selected at the same time (doesn't matter which TableView it is selected from). I was thinking about some kind of listener which deselects the other row when a row is selected. This is my initial setup:

第1步
搜索将方法绑定到行选择的方法(那里不是像 tableview.setOnRowSelected(方法)

第2步
创建一个类似于一种监听器的方法:当选择一行时,取消选择另一行(我知道如何做这部分)

Step 2 Create the method which acts like a kind of listener: when a row is selected, deselect the other row (I know how to do this part)

Class1 selectedObject1 = (Class1)tableview1.getSelectionModel().getSelectedItem();
Class2 selectedObject2 = (Class2)tableview2.getSelectionModel().getSelectedItem();

if(selectedObject1 != null && selectedObject2 != null) {
   tableview1.getSelectionModel().clearSelection();
}

因此,第一步就是问题所在。我想到了一个可以在其上创建监听器的可观察列表,然后将所选行添加到列表中。发生这种情况时,侦听器可以调用该方法。
任何人都知道怎么做这个?

So, step one is the problem. I was thinking of an observable list on which a listener can be created, and then add the selected row to the list. When this happens, the listener can call the method. Anyone any clue how to make this?

非常感谢任何帮助。

推荐答案

选择模型中的 selectedItem 是一个可观察的属性,因此您应该可以通过以下方式实现此目的:

The selectedItem in the selection model is an observable property, so you should be able to achieve this with:

tableview1.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
    if (newSelection != null) {
        tableview2.getSelectionModel().clearSelection();
    }
});

tableview2.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
    if (newSelection != null) {
        tableview1.getSelectionModel().clearSelection();
    }
});

这篇关于JavaFX8:如何在Tableview中创建用于选择行的侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆