Question

I am using JScrollPane and populating it through Model..Now I want to add Double CLick Listener Here how I am trying...

  PlayListScrollPane.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                JList theList = (JList) mouseEvent.getSource();
                if (mouseEvent.getClickCount() == 2) {
                    int index = theList.locationToIndex(mouseEvent.getPoint());
                    if (index >= 0) {
                        Object o = theList.getModel().getElementAt(index);
                        System.out.println("Double-clicked on: " + o.toString());
                    }
                }
            }
        });

PlayListScrollPane is JScrollPane... The above method never fires up... THanks.

Was it helpful?

Solution 4

OK..I got it fixed, actually I was adding the MouseListener in wrong class. I simply followed this tut and achieved what I wanted.

OTHER TIPS

Your problem is that your clickCount should be a variable from the class not inside the listener. Just like:

private clicksCount = 0;

And you can acces the list if it's instantiated too. Then:

PlayListScrollPane.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent mouseEvent) {
        clicksCount++;

        if (clicksCount == 2) { //Or clicksCount%2==0
            int index = myJList.locationToIndex(mouseEvent.getPoint());
            if (index >= 0) {
                Object o = theList.getModel().getElementAt(index);
                System.out.println("Double-clicked on: " + o.toString());
            }
            clicksCount=0;//If you use clickCounts%2==0 you don't need this line
        }
    }
});

You probably should add the listener to the viewport instead of the scroll pane

try this :

PlayListScrollPane.getViewport().addMouseListener(new MouseAdapter() { ...

instead of :

PlayListScrollPane.addMouseListener(new MouseAdapter() { ... 

JList theList = (JList) mouseEvent.getSource();

It looks like you have a JList being displayed in the scrollpane. A JList uses a MouseListener so it will handle the MouseEvents. If you want to do some processing on the JList with a double click then add the MouseListener to the JList.

Actually check out List Action for a better approach. It will allow you to create an Action and then support the invoking of the Action by using a double click or the Enter key, since a well designed GUI should work by mouse or keyboard.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top