gpt4 book ai didi

java - JPopupMenu 不起作用

转载 作者:行者123 更新时间:2023-12-01 17:37:03 25 4
gpt4 key购买 nike

我编写了一个简单的程序来了解 JPopupMenu 的工作原理。但我的代码有问题,它没有正确显示弹出菜单。请问谁能告诉我原因吗?

public class PopUpMenu extends JFrame implements ActionListener {

JPanel panel;
JPopupMenu popMenu;
JMenuItem cut;
JMenuItem copy;

public PopUpMenu() {

setVisible(true);
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);

panel = new JPanel();
popMenu = new JPopupMenu();
cut = new JMenuItem();
popMenu.add(cut);
copy = new JMenuItem();
popMenu.add(copy);

add(panel);
panel.setComponentPopupMenu(popMenu);

addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent Me) {
if (Me.isPopupTrigger()) {
popMenu.show(Me.getComponent(), Me.getX(), Me.getY());
}
}
});

}

public void actionPerformed(ActionEvent arg0) {

}

public static void main(String[] args) {

Runnable r = new Runnable() {
public void run() {
PopUpMenu pop = new PopUpMenu();
}
};
SwingUtilities.invokeLater(r);

}

}

最佳答案

您的代码是完美的(不需要鼠标监听器,并且应该将面板添加到 JFrame 的内容 Pane 中),但它可以工作。如果您为菜单项提供一些文本,也许效果会更好:

cut = new JMenuItem("Cut");

关于java - JPopupMenu 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5243218/

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