检测双击 TableView JavaFX 行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26563390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:48:49  来源:igfitidea点击:

Detect doubleclick on row of TableView JavaFX

javatableviewjavafx-8

提问by Marcos

I need to detect double clicks on a row of a TableView.

我需要检测对 a 行的双击TableView

How can I listen for double clicks on any part of the row and get all data of this row to print it to the console?

如何侦听该行任何部分的双击并获取该行的所有数据以将其打印到控制台?

采纳答案by James_D

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 ;
});

Here is a complete working example:

这是一个完整的工作示例:

import java.util.Random;
import java.util.function.Function;

import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

public class TableViewDoubleClickOnRow extends Application {

    @Override
    public void start(Stage primaryStage) {
        TableView<Item> table = new TableView<>();
        table.setRowFactory(tv -> {
            TableRow<Item> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && (! row.isEmpty()) ) {
                    Item rowData = row.getItem();
                    System.out.println("Double click on: "+rowData.getName());
                }
            });
            return row ;
        });
        table.getColumns().add(column("Item", Item::nameProperty));
        table.getColumns().add(column("Value", Item::valueProperty));

        Random rng = new Random();
        for (int i = 1 ; i <= 50 ; i++) {
            table.getItems().add(new Item("Item "+i, rng.nextInt(1000)));
        }

        Scene scene = new Scene(table);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private static <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> property) {
        TableColumn<S,T> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
        return col ;
    }

    public static class Item {
        private final StringProperty name = new SimpleStringProperty();
        private final IntegerProperty value = new SimpleIntegerProperty();

        public Item(String name, int value) {
            setName(name);
            setValue(value);
        }

        public StringProperty nameProperty() {
            return name ;
        }

        public final String getName() {
            return nameProperty().get();
        }

        public final void setName(String name) {
            nameProperty().set(name);
        }

        public IntegerProperty valueProperty() {
            return value ;
        }

        public final int getValue() {
            return valueProperty().get();
        }

        public final void setValue(int value) {
            valueProperty().set(value);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

回答by Alexander.Berg

Example:

例子:

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

If you are using custom selection model, then you can get the row from event, example:

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

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());
        }
    }
});

回答by Sushal Penugonda

If you are using SceneBuilderyou can set your table's OnMouseClickedto handleRowSelect()method as shown below:

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

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();
        }
    }
}

回答by Aubin

This answer has been tested:

这个答案已经过测试:

table.setOnMouseClicked( event -> {
   if( event.getClickCount() == 2 ) {
      System.out.println( table.getSelectionModel().getSelectedItem());
   }});

table.getSelectionModel().getSelectedItem()can be use since we catch a double-click. One the first click the selection moves, on the second this handler is executed.

table.getSelectionModel().getSelectedItem()可以使用,因为我们捕获了双击。第一次单击选择移动,第二次执行此处理程序。

回答by Abdul.Moqueet

This works for me:

这对我有用:

table.setOnMouseClicked((MouseEvent event) -> {
            if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2){
                System.out.println(table.getSelectionModel().getSelectedItem());
            }
        });
    }

回答by nayasis

I had similar situation not to detect mouse double click event on TableView. Above all samples worked perfectly. but my application did not detect double click event at all.

我有类似的情况没有检测到 TableView 上的鼠标双击事件。最重要的是,所有样品都完美无缺。但我的应用程序根本没有检测到双击事件。

But I found that if TableView is on editable, mouse double click event can not be detected !!

但是我发现如果 TableView 处于可编辑状态,则无法检测到鼠标双击事件!

check your application if TableView is on editable like this.

如果 TableView 处于可编辑状态,请检查您的应用程序。

tableView.setEditable( true );

if then, double click event only raises on same row selected.

如果那样,双击事件只会在选定的同一行上引发。