检测TableView JavaFX行上的doubleclick

我需要检测双击TableView的一行。

我怎样才能听到在行的任何部分双击,并获得该行的所有数据打印到控制台?

 TableView<MyType> table = new TableView<>(); //... table.setRowFactory( tv -> { TableRow<MyType> row = new TableRow<>(); row.setOnMouseClicked(event -> { if (event.getClickCount() == 2 && (! row.isEmpty()) ) { MyType rowData = row.getItem(); System.out.println(rowData); } }); return row ; }); 

例:

 table.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isPrimaryButtonDown() && event.getClickCount() == 2) { System.out.println(table.getSelectionModel().getSelectedItem()); } } }); 

如果您使用自定义select模型,则可以从事件中获取该行,例如:

 table.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isPrimaryButtonDown() && event.getClickCount() == 2) { Node node = ((Node) event.getTarget()).getParent(); TableRow row; if (node instanceof TableRow) { row = (TableRow) node; } else { // clicking on text part row = (TableRow) node.getParent(); } System.out.println(row.getItem()); } } }); 

如果您正在使用SceneBuilder ,则可以将您的表的OnMouseClicked设置为handleRowSelect()方法,如下所示:

 MyType temp; Date lastClickTime; @FXML private void handleRowSelect() { MyType row = myTableView.getSelectionModel().getSelectedItem(); if (row == null) return; if(row != temp){ temp = row; lastClickTime = new Date(); } else if(row == temp) { Date now = new Date(); long diff = now.getTime() - lastClickTime.getTime(); if (diff < 300){ //another click registered in 300 millis System.out.println("Edit dialog"); } else { lastClickTime = new Date(); } } }