how to differentiate between a single click or double click on a table row in javafx

前端 未结 2 643
一向
一向 2021-01-26 11:44

I am trying to create a table in javafx that allows a user to click on a row to go to one page or double click the row to go to a different page. The problem is that the applica

2条回答
  •  逝去的感伤
    2021-01-26 12:26

    There's no way to do this that's part of the API: you just have to code "have the program wait and see if there is another click" yourself. Note that this means that the single-click action has to have a slight pause before it's executed; there's no way around this (your program can't know what's going to happen in the future). You might consider a different approach (e.g. left button versus right button) to avoid this slightly inconvenient user experience.

    However, a solution could look something like this:

    public class DoubleClickHandler {
    
        private final PauseTransition delay ;
        private final Runnable onSingleClick ;
        private final Runnable onDoubleClick ;
        private boolean alreadyClickedOnce ;
    
        public DoubleClickHandler(
            Duration maxTimeBetweenClicks,
            Runnable onSingleClick,
            Runnable onDoubleClick) {
    
            alreadyClickedOnce = false ;
            this.onSingleClick = onSingleClick ;
            this.onDoubleClick = onDoubleClick ;
    
            delay = new PauseTransition(maxTimeBetweenClicks);
            delay.setOnFinished(e -> {
                alreadyClickedOnce = false ;
                onSingleClick.run()
            });
        }
    
        public void applyToNode(Node node) {
            node.setOnMouseClicked(e -> {
                delay.stop();
                if (alreadyClickedOnce) {
                    alreadyClickedOnce = false ;
                    onDoubleClick.run();
                } else {
                    alreadyClickedOnce = true ;
                    delay.playFromStart();
                }
            });
        }
    }
    

    Which you can use with:

    searchResults.setRowFactory(tv -> {
        TableRow row = new TableRow<>();
        DoubleClickHandler handler = new DoubleClickHandler(
            Duration.millis(500),
            () -> {
                MovieRow tempResult = row.getItem();
                System.out.println(tempResult.getMTitle + " was clicked once");
            },
            () -> {
                MovieRow tempResult = row.getItem();
                System.out.println(tempResult.getMTitle + " was clicked twice");
            }
        );
        handler.applyToNode(row);
        return row ;
    });
    

提交回复
热议问题