简体   繁体   中英

How to add Double-click capability in JScrollPane?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM