如何在Java Swing中创建右键单击上下文菜单? [英] How do I create a right click context menu in Java Swing?

查看:184
本文介绍了如何在Java Swing中创建右键单击上下文菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个右键单击上下文菜单,右键单击并实例化一个新的 JMenu ,并将其位置设置为鼠标位置的位置...是否存在更好的方法?

I'm currently creating a right-click context menu by instantiating a new JMenu on right click and setting its location to that of the mouse's position... Is there a better way?

推荐答案

您可能是手动调用 setVisible(true)在菜单上。这可能会导致菜单中出现一些讨厌的错误行为。

You are probably manually calling setVisible(true) on the menu. That can cause some nasty buggy behavior in the menu.

show(Component,int x,int x)方法处理你需要发生的所有事情, (在鼠标悬停时突出显示内容并在必要时关闭弹出窗口)使用 setVisible(true)只显示菜单而不添加任何其他行为。

The show(Component, int x, int x) method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where using setVisible(true) just shows the menu without adding any additional behavior.

要制作一个右键单击弹出菜单,只需创建一个 JPopupMenu

To make a right click popup menu simply create a JPopupMenu.

class PopUpDemo extends JPopupMenu {
    JMenuItem anItem;
    public PopUpDemo(){
        anItem = new JMenuItem("Click Me!");
        add(anItem);
    }
}

然后,您需要做的就是添加一个自定义 MouseListener 您希望弹出菜单的组件。

Then, all you need to do is add a custom MouseListener to the components you would like the menu to popup for.

class PopClickListener extends MouseAdapter {
    public void mousePressed(MouseEvent e){
        if (e.isPopupTrigger())
            doPop(e);
    }

    public void mouseReleased(MouseEvent e){
        if (e.isPopupTrigger())
            doPop(e);
    }

    private void doPop(MouseEvent e){
        PopUpDemo menu = new PopUpDemo();
        menu.show(e.getComponent(), e.getX(), e.getY());
    }
}

// Then on your component(s)
component.addMouseListener(new PopClickListener());

当然,教程有稍微深入一点的解释。

Of course, the tutorials have a slightly more in-depth explanation.

注意:如果您发现弹出菜单与用户点击的位置相差不远,请尝试使用 e.getXOnScreen() e.getYOnScreen() x和y坐标的方法。

Note: If you notice that the popup menu is appearing way off from where the user clicked, try using the e.getXOnScreen() and e.getYOnScreen() methods for the x and y coordinates.

这篇关于如何在Java Swing中创建右键单击上下文菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆