如何只在JPopupMenu中左键单击选择JMenuItem?

时间:2016-12-08 00:37:57

标签: java swing jmenuitem jpopupmenu

我想通过右键单击桌面上的菜单(它在示例中正常工作),但我想只使用左键单击来设置menitems(并通过右键单击取消菜单,但现在离开并右键单击两者调用操作)。

我该怎么做?我尝试过MouseListeners但是我无法使它工作。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

public class PopupDemo {

    protected void initUI() {
        final JFrame frame = new JFrame(PopupDemo.class.getSimpleName());
        Vector<String> columns = new Vector<String>(Arrays.asList("Coumn 1", "Column 2"));
        Vector<Vector<String>> data = new Vector<Vector<String>>();
        for (int i = 0; i < 5; i++) {
            Vector<String> row = new Vector<String>();
            for (int j = 0; j < columns.size(); j++) {
                row.add("Cell " + (i + 1) + "," + (j + 1));
            }
            data.add(row);
        }
        final JTable table = new JTable(data, columns);
        final JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem deleteItem = new JMenuItem("Delete");
        deleteItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "DELETE OPTION CHOOSED");
            }
        });
        popupMenu.add(deleteItem);
        table.setComponentPopupMenu(popupMenu);
        frame.add(new JScrollPane(table), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new PopupDemo().initUI();
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

在deleteItem上你要做的是检查MouseListener里面单击了哪个鼠标按钮

 deleteItem.addMouseListener(new MouseAdapter() {
           @Override
           public void mousePressed(MouseEvent e) {
              if (e.getButton() == MouseEvent.BUTTON3) {
                 // do whatever it is when the right button is pressed
              } else {
                // do whatever it is when the left button is pressed
              }
           }
        });