Search code examples
javaswingmenuawtjpopupmenu

Popup on left click


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());
            }
        });

Solution

  • Component source = (Component)evt.getSource();
    Point location = MouseInfo.getPointerInfo().getLocation();
    SwingUtilities.convertPointFromScreen(location, source
    Pmenu.show(source, 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.

    Component source = (Component)evt.getSource();
    Point location = source.getLocation();
    Dimension size = source.getSize();
    
    int xPos = location.x + ((size.width - PMenu.getWidth()) / 2;
    int yPos = location.y + size.height;
    Pmenu.show(source, xPos, yPos);
    

    This is, of course, just an example, you would be able to supply your layout information as you please

    WORKING UPDATE

        Component source = (Component)evt.getSource(); 
        Dimension size = source.getSize(); 
    
        int xPos = ((size.width - Pmenu.getPreferredSize().width) / 2); 
        int yPos = size.height;
    
        Pmenu.show(source, xPos, yPos);
    

    Because the popup location is relative to the source, we don't need the source's location information