JPOupMenu在mouseEntered上消失

时间:2013-10-09 14:28:33

标签: java swing jpanel jpopupmenu

我有下一个结构:JPopupMenu包含JPanel,其中包含JMenuItems。问题是,我无法使用它,因为JPopupMenumouse enters任意menu item时消失。

SSCCE:

public class PopupTest {
    public static void main(String[] a) {
        final JFrame frame = new JFrame();
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createLineBorder(Color.RED));

        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    final JPopupMenu menu = new JPopupMenu();
                    JPanel menuPanel = new JPanel();
                    menuPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN));
                    menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));

                    for (int i = 0; i < 10; i++) {
                        JMenuItem item = new JMenuItem(String.valueOf(i));
                        menuPanel.add(item);
                    }

                    menu.add(menuPanel);
                    menu.show(panel, e.getX(), e.getY());
                }
            }
        });
        frame.setContentPane(panel);
        frame.setUndecorated(true);
        frame.setBackground(new Color(50, 50, 50, 200));

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
    }
}

顺便说一句,当JPanel与其项目之间没有JPopupMenu时,问题不会重复。

有谁知道如何预防?

2 个答案:

答案 0 :(得分:1)

不是直接回答您的问题,但我认为,当您支持panel直接向其添加JPopupMenu时,您会在JMenuitem上不必要地添加 final JPopupMenu menu = new JPopupMenu(); JPanel menuPanel = new JPanel(); menuPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN)); // menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS)); for (int i = 0; i < 10; i++) { JLabel item = new JLabel(i+""); menuPanel.add(item); } menu.add(menuPanel); menu.show(panel, e.getX(), e.getY()); 。检查以下代码片段:

{{1}}

答案 1 :(得分:1)

一些提示:

  • 每次按下按钮时,只需定义一次弹出菜单。

  • 您需要覆盖mouseReleasedmousePressed方法:Bringing Up a Popup Menu

  • 使用MouseEvent.isPopupTrigger查看是否应显示弹出窗口。

  • menuItems直接添加到menu,而不是JPanel

建议更改:

    final JPopupMenu menu = new JPopupMenu();
    menu.setLayout(new GridLayout(2,5)); // How do you can, for example, lay out your menu items horizontally in 2 rows?
    for (int i = 0; i < 10; i++) {
        JMenuItem item = new JMenuItem(String.valueOf(i));
        menu.add(item);
    }

    MouseListener mouseListener = new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if(e.isPopupTrigger()){
                menu.show(panel, e.getX(), e.getY());
            }
        }
    };

    panel.addMouseListener(mouseListener);

<强>图片

enter image description here