Frage

I'm trying to center a JMenu's popup so I can use it on a JPanel and it doesn't look off. Here is some code that demos what I am trying to do:

import javax.swing.*;

public class Menu extends JMenu{

public static void main(String[] args) {        
    JFrame f = new JFrame("Menu Test");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(new Menu());

    JPanel background = new JPanel();
    background.add(menuBar);
    f.setContentPane(background);

    f.setSize(250, 100);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

public Menu() {
    super("I'm a Menu");

    add(new JMenuItem("Can This Popup be Centered?"));
    add(new JMenuItem("Not To the Right?"));
}
}

Here's the current output

Here is an image of the output

Here's what I want (or close to)

Here is (close to) what I want

If there is a better way to do this other than using a JMenu, please let me know. Thanks.

War es hilfreich?

Lösung

I figured out the answer. I override processMouseEvent to know when the menu was clicked, and than simply set the location of the popup menu relative to the location of the menu.

    @Override
    protected void processMouseEvent(MouseEvent e) {
        super.processMouseEvent(e);
        if(e.getID() == MouseEvent.MOUSE_PRESSED)
            getPopupMenu().setLocation(
                getLocationOnScreen().x+getWidth()/2-getPopupMenu().getWidth()/2,
                getLocationOnScreen().y+getHeight());
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top