【问题标题】:How would you center a JMenu's Popup?您如何将 JMenu 的弹出窗口居中?
【发布时间】:2013-03-14 13:20:22
【问题描述】:

我正在尝试使 JMenu 的弹出窗口居中,这样我就可以在 JPanel 上使用它并且它不会消失。这是一些演示我正在尝试做的代码:

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?"));
}
}

这是当前的输出

这就是我想要(或接近)的东西

如果有比使用 JMenu 更好的方法,请告诉我。 谢谢。

【问题讨论】:

  • 小心:非标准的用户界面容易混淆用户
  • @kleopatra 我正在做一个类似于 Microsoft Paint 的项目,我正在使用菜单显示一个用于设置宽度的弹出窗口,这很像 Paint 的做法。

标签: java swing alignment center jmenu


【解决方案1】:

我想出了答案。我重写 processMouseEvent 以了解何时单击菜单,而不是简单地设置弹出菜单相对于菜单位置的位置。

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

【讨论】:

    猜你喜欢
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多