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代码是显示一个带有两个项目的弹出菜单,但是当我右键点击框架时没有显示弹出菜单,请帮忙。
答案 0 :(得分:4)
来自Java Doc:isPopupTrigger()
弹出菜单在不同系统上的触发方式不同。因此,应该在mousePressed和mouseReleased中检查isPopupTrigger以获得正确的跨平台功能。
而不是mouseClicked()在下面添加两个方法:
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());
}