Andrew Falanga
Andrew Falanga

Reputation: 75

Proper way to implement mouse events

I have code, it's below, that displays a photograph in the JPanel. Actually, the JPanel is walking through a photo album and I have it so that when the JPanel is clicked on, the panel advances to the next frame. I also have it configured so that if the JPanel is right-clicked on, a popup menu is displayed.

I read that, when implementing a popup menu, one needs to override both mousePressed() and mouseReleased() in order to catch the trigger for all platforms. However, since I have a listener associated with the JPanel, when the user clicks the window the JPanel advances two photos. This is understandable, but how should I code this so that I ensure I display the popup on all platforms (my professor may check my program on Linux and I have to code it on Windows at home).

Upvotes: 3

Views: 177

Answers (2)

kleopatra
kleopatra

Reputation: 51535

JComponents have a property componentPopupMenu - setting that property makes your popupMenu appear automatically, without requiring any effort in a MouseListener

 photoPanel.setComponentPopupMenu(photoPopupMenu);

Then make sure that your mouse-triggered action (advancing to the next) happens only on single left pressed.

Upvotes: 3

MeBigFatGuy
MeBigFatGuy

Reputation: 28598

Use

MouseEvent.isPopupTrigger() 

to determine if for the platform the given event should be used to show the popup.

You would put this in each method (mousePressed and mouseReleased)

Upvotes: 2

Related Questions