猿问

javafx:双击空白行打开先前选择的对象

给定一个 TableView,我需要检测双击才能打开相关对象的新窗口。


但是,如果我选择一个对象,然后单击 tableview 的空白区域,它将打开我之前选择的对象。


我一直在环顾四周,每个人都为 tableview 定义了一个对象行,当该行为空 ( row.isEmpty()) 时,他们解决了问题。


所以,我的问题是:我可以在不指定 TableView 的行的情况下做同样的事情吗?


这是我的桌子的控制器:


我是意大利人,所以有些东西是用意大利语写的(比如对象和变量名称)我用以下注释突出显示了对创建表很重要的部分:/****部分表视图****/


慕容708150
浏览 175回答 1
1回答

一只萌萌小番薯

在一个空行的原因双击使你打开最后选定的产品,因为你加入EventHandler到TableView。当您单击 上的任意位置TableView(包括空行)时,将EventHandler调用 。您想要的是每行EventHandler检查该行是否为空。此外,由于每个TableRow都有对其项目的引用,因此您不必使用TableView的选择模型。下面是一个例子:import javafx.event.EventHandler;import javafx.fxml.FXML;import javafx.scene.control.TableRow;import javafx.scene.control.TableView;import javafx.scene.input.MouseButton;import javafx.scene.input.MouseEvent;public class Controller {&nbsp; @FXML&nbsp; private TableView<Object> table; // Using <Object> for example&nbsp; @FXML&nbsp; private void initialize() {&nbsp; &nbsp; EventHandler<MouseEvent> onClick = this::handleTableRowMouseClick;&nbsp; &nbsp; table.setRowFactory(param -> {&nbsp; &nbsp; &nbsp; TableRow<Object> row = new TableRow<>();&nbsp; &nbsp; &nbsp; row.setOnMouseClicked(onClick);&nbsp; &nbsp; &nbsp; return row;&nbsp; &nbsp; });&nbsp; }&nbsp; private void handleTableRowMouseClick(MouseEvent event) {&nbsp; &nbsp; if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {&nbsp; &nbsp; &nbsp; // We know it will be a TableRow<Object> since that is the only kind&nbsp; &nbsp; &nbsp; // of object we added the EventHandler to.&nbsp; &nbsp; &nbsp; @SuppressWarnings("unchecked")&nbsp; &nbsp; &nbsp; TableRow<Object> row = (TableRow<Object>) event.getSource();&nbsp; &nbsp; &nbsp; if (!row.isEmpty() && row.getItem() != null) {&nbsp; &nbsp; &nbsp; &nbsp; displayItem(row.getItem());&nbsp; &nbsp; &nbsp; &nbsp; event.consume();&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; private void displayItem(Object item) {&nbsp; &nbsp; // This is where you'd put your code that opens the item in&nbsp; &nbsp; // its own Stage.&nbsp; }}在示例中,EventHandler与TableRow由rowFactory. 这是可以的,因为我们可以TableRow通过调用MouseEvent.getSource(). 我将事情分成更多的方法,以使代码更具可读性/可维护性。该示例检查鼠标按钮是否为主按钮。如果您不关心哪个按钮被点击了两次,那么您可以简单地删除该检查。
随时随地看视频慕课网APP

相关分类

Java
我要回答