JPopupMenu菜单不出现

问题描述 投票:0回答:2

这是我的JPopupMenu的代码以及我的添加方式,当我右键单击该表时,它应该会响应:

    JMenuItem deleteRows = new JMenuItem("Delete Row");
    popup.add(deleteRows);

    personTable.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            if(e.getButton() == MouseEvent.BUTTON3) {
                popup.show(personTable, e.getX(), e.getY());
            }
        }

    });

我不确定在应用程序中的表上单击鼠标右键时,为什么没有出现弹出菜单。如果有人告诉我我做错了,我将不胜感激。

java swing jtable jpopupmenu
2个回答
2
投票

弹出窗口的触发因不同的操作系统而异,您不能简单地使用mousePressed,并且您当然不应该使用e.getButton() == MouseEvent.BUTTON3

来自How to use Menus, Bringing up a PopupMenu

应该显示弹出菜单的确切手势因外观而异。在Microsoft Windows中,按照惯例,用户将光标悬停在启用了弹出框的组件上,并通过释放鼠标右键来弹出弹出菜单。在Java外观中,惯用触发器是按下鼠标右键(对于释放按钮后弹出的弹出窗口)或单击它(对于弹出的弹出窗口)。

相反,您应该检查每个鼠标事件pressedreleasedclicked。您还应该使用MouseEvent#isPopupTrigger确定事件是否是操作系统的弹出式触发器。

说了这么多,只给我们JComponent#setComponentPopupMenu做决定就可以了

JComponent#setComponentPopupMenu

可运行的示例...

personTable.setComponentPopupMenu(popup);

Popup

0
投票

这是不使用鼠标侦听器即可创建popupMenu的简单方法:

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                DefaultTableModel model = new DefaultTableModel(10, 10);
                JTable table = new JTable(model);

                JMenuItem mi = new JMenuItem("I'll be your menu for today");
                JPopupMenu popup = new JPopupMenu();
                popup.add(mi);

                table.setComponentPopupMenu(popup);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.