I am trying to make a set of navigation buttons for a file browser. I want it so that if the user clicks the dedicated history button, a JPopupMenu appears. However, I also want that exact same menu to appear when the user right-clicks or drags the cursor down the back or forward button. How can I make that exact same JPopupMenu (not a copy, but the same exact one) appear for multiple GUI components for different gestures?
So far I've tried the following:
histButton.addMouseListener(new MouseAdapter()
{
@Override public void mouseClicked(MouseEvent e)
{
showPopup(e);
}
@Override public void mouseDragged(MouseEvent e)
{
showPopup(e);
}
private void showPopup(MouseEvent e)
{
histPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
forwardButton.addMouseListener(new MouseAdapter()
{
@Override public void mouseClicked(MouseEvent e)
{
if (e.isPopupTrigger())
showPopup(e);
}
@Override public void mouseDragged(MouseEvent e)
{
showPopup(e);
}
private void showPopup(MouseEvent e)
{
histPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
backButton.addMouseListener(new MouseAdapter()
{
@Override public void mouseClicked(MouseEvent e)
{
if (e.isPopupTrigger())
showPopup(e);
}
@Override public void mouseDragged(MouseEvent e)
{
showPopup(e);
}
private void showPopup(MouseEvent e)
{
histPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
All components are added and display correctly, and debugging shows me that they register the events, but no menu appears.
Bringing Up a Popup Menu shows the traditional implementation using
mousePressed()
,mouseReleased()
andisPopupTrigger()
. Note that "The exact gesture that should bring up a popup menu varies by look and feel." You might compare what's shown with your implementation, which usesmousePressed()
.Addendum: For reference, @mKorbel recalls this client property that may prove useful.