Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a mouse doubleclick event listener to the cells of a ListView in javafx?

I have a list of links in a ListView. I want to add an mouseEventListener to each cell of the list so that whenever a user double clicks the list item link is opened. I can write the functionality of opening the link on my own but I am not able to add the doubleclick event with every cell in the list. Please help...

like image 436
Krishna Avatar asked Mar 20 '14 18:03

Krishna


2 Answers

Let us consider your ListView as playList. Now you can implement the mouse listener with double click functionality on each cell using

playList.setOnMouseClicked(new EventHandler<MouseEvent>() {

    @Override
    public void handle(MouseEvent click) {

        if (click.getClickCount() == 2) {
           //Use ListView's getSelected Item
           currentItemSelected = playList.getSelectionModel()
                                                    .getSelectedItem();
           //use this to do whatever you want to. Open Link etc.
        }
    }
});
like image 65
ItachiUchiha Avatar answered Nov 10 '22 04:11

ItachiUchiha


I had to solve the same sort of issue, my ListView contains a grid pane and labeled text so you'll have to change the 'instanceof' and the other side of the 'or' to what you have.

(Assuming your ListView is named listView):

listView.setOnMouseClicked(new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent event) {
        if(event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2 &&
           (event.getTarget() instanceof LabeledText || ((GridPane) event.getTarget()).getChildren().size() > 0)) {

           //your code here        
         }    
    }
});

It is possible if the user clicks near the very edge of the item and the border of the ListView for it not to pass the if loop but it sounds like the user won't be doing that in your case.

Hope this helps.

like image 37
Jay Avatar answered Nov 10 '22 04:11

Jay