Java swing popup menu and jlist

VaclavDedik picture VaclavDedik · May 15, 2011 · Viewed 20.6k times · Source

here is my problem: I have a jList and a popup menu. When I right click the jList, the popup menu shows. The problem is that the jList item which the mouse is pointing at won't select. And I want it to do that. When I point my cursor at an item in the list and press the right button, I want two things to happen. Select the item on which I clicked and show the popup menu.

I tried this:

jLists.addMouseListener(new MouseAdapter() {

     @Override
     public void mousePressed(MouseEvent e) {
            jList.setSelectedIndex(jList.locationToIndex(e.getPoint()));
     }
});

jList.setComponentPopupMenu(jPopupMenu);

But it only shows the popup menu. If I delete this line:

jList.setComponentPopupMenu(jPopupMenu);

then the right-click select works (but the popup menu doesn't show).

So, what do you think is the best way to make these two functions (both) work ?

Thanks and sorry for my english.

Answer

Alba Mendez picture Alba Mendez · May 15, 2011

Don't do setComponentPopupMenu. In the MouseAdapter do the following:

public void mousePressed(MouseEvent e)  {check(e);}
public void mouseReleased(MouseEvent e) {check(e);}

public void check(MouseEvent e) {
    if (e.isPopupTrigger()) { //if the event shows the menu
        jList.setSelectedIndex(jList.locationToIndex(e.getPoint())); //select the item
        jPopupMenu.show(jList, e.getX(), e.getY()); //and show the menu
    }
}

This should work.

EDIT: The code now checks both press and release events, because some platforms show popups when mouse presses and some other on release. See the Swing tutorial for more info.