本文介绍了右键单击不显示JPopupMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class B extends MouseAdapter {
JFrame frame = new JFrame();
JPopupMenu popup = new JPopupMenu();
JMenuItem item1 = new JMenuItem("ADD");
JMenuItem item2 = new JMenuItem("DELETE");
public static void main(String arg[]) {
new B();
}
B() {
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLayout(new FlowLayout());
frame.addMouseListener(this);
popup.add(item1);
popup.add(item2);
frame.add(popup);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent click) {
if(click.isPopupTrigger())
popup.show(frame,click.getX(),click.getY());
}
}
我写过这个java代码是显示一个包含两个项目的弹出菜单,但是当我右键单击框架时不会显示弹出菜单,请帮助。
I have written this java code is to display a popup menu with two items on it, but popup menu is not displayed when I right click on frame, please help.
推荐答案
来自Java Doc:
From Java Doc : isPopupTrigger()
弹出菜单在不同系统上的触发方式不同。因此,应该在mousePressed和mouseReleased中检查isPopupTrigger以获得正确的跨平台功能。
Popup menus are triggered differently on different systems. Therefore, isPopupTrigger should be checked in both mousePressed and mouseReleased for proper cross-platform functionality.
而不是mouseClicked()在下面添加两种方法:
Instead of mouseClicked() add below two methods:
public void mousePressed(MouseEvent e) {
if(e.isPopupTrigger())
popup.show(frame,e.getX(),e.getY());
}
public void mouseReleased(MouseEvent e) {
if(e.isPopupTrigger())
popup.show(frame,e.getX(),e.getY());
}
这篇关于右键单击不显示JPopupMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!