I am trying to create a popup on a button through the action listener with Java.
I have some code, but I can’t get it to work, though I think I’m close!
This code is from an example but for Pmenu.show, I had to remove the first arg, and I don’t know what to replace it with, which seems to be the problem here.
btnOptions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JPopupMenu Pmenu = new JPopupMenu();
JMenuItem menuItem = new JMenuItem("Cut");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Copy");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Paste");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Delete");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Undo");
Pmenu.add(menuItem);
Point location = MouseInfo.getPointerInfo().getLocation();
Pmenu.show(null, location.getX(), location.getY());
}
});
The question that jumps out at me is “why?” Why do it this way? What is it your are trying to achieve?
UPDATE – Popup offset
This would display the popup centered horizontally against the source control (the button) and under it.
This is, of course, just an example, you would be able to supply your layout information as you please
WORKING UPDATE
Because the popup location is relative to the source, we don’t need the source’s location information