I have a java program that opens a popup menu when right clicked in a JPanel. When any of the popup menu items are clicked, I want to print the location of the right click that triggered the popupmenu in the terminal. How do I do this? How do I get the location of where the right click happened from within popup action events?
How does the code change if the popup menu is in a JComponent?
Here is the program.
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
public class MenuTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MenuFrame frame = new MenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class MenuFrame extends JFrame
{
public MenuFrame()
{
setTitle("MenuTest");
setSize(300, 200);
Action cutAction = new TestAction("Cut");
Action copyAction = new TestAction("Copy");
Action pasteAction = new TestAction("Paste");
JPopupMenu popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);
JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
panel.addMouseListener(new MouseAdapter() {});
}
class TestAction extends AbstractAction
{
public TestAction(String name)
{
super(name);
}
public void actionPerformed(ActionEvent event)
{
System.out.println("Right click happened at ?"); // How do I get right click location?
}
}
}
Add a mouse listener to pressed events, (clicked events get captured by popup):
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
clickLocation.setSize(e.getX(), e.getY());
}
});
Action cutAction = new TestAction("Cut", clickLocation);
Action copyAction = new TestAction("Copy", clickLocation);
Action pasteAction = new TestAction("Paste", clickLocation);
Print out the dimension:
private Dimension clickLocation;
public TestAction(String name, Dimension clickLocation) {
super(name);
this.clickLocation = clickLocation;
}
public void actionPerformed(ActionEvent event) {
System.out.println("Right click happened at " + clickLocation);
}
you were on the right track. i personally prefer to show it manually in the MouseAdapter
so i can add methods on other mouseevents. for this you probably need to remove the panel.setComponentPopupMenu(popup);
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
if (arg0.getButton() == MouseEvent.BUTTON3) { //Button3 is rightclick
popup.show(panel, arg0.getX(), arg0.getY());
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With