gpt4 book ai didi

java - JPopupMenu 菜单不出现

转载 作者:行者123 更新时间:2023-12-02 04:25:27 28 4
gpt4 key购买 nike

这是我的 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());
}
}

});

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

最佳答案

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

来自How to use Menus, Bringing up a PopupMenu

The exact gesture that should bring up a popup menu varies by look and feel. In Microsoft Windows, the user by convention brings up a popup menu by releasing the right mouse button while the cursor is over a component that is popup-enabled. In the Java look and feel, the customary trigger is either pressing the right mouse button (for a popup that goes away when the button is released) or clicking it (for a popup that stays up).

相反,您应该检查每个鼠标事件:按下释放点击。您还应该使用 MouseEvent#isPopupTrigger 来确定该事件是否是操作系统的弹出触发器。

话虽如此,只有我们 JComponent#setComponentPopupMenu 会更简单。并让它决定

personTable.setComponentPopupMenu(popup);

可运行示例...

Popup

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

}

关于java - JPopupMenu 菜单不出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32240478/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com