当前位置: 技术问答>java相关
怎样制作弹出菜单(pop-up menu)?
来源: 互联网 发布时间:2017-03-17
本文导语: 在一个地方点击右键,就弹出一个菜单,请问应该怎么做,能给一点例子吗? | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PopupDemo extends JFrame { public PopupDemo() { Contain...
在一个地方点击右键,就弹出一个菜单,请问应该怎么做,能给一点例子吗?
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupDemo extends JFrame
{
public PopupDemo()
{
Container contentPane = getContentPane();
final JLabel label = new JLabel("Click here");
label.setHorizontalAlignment(JLabel.CENTER);
final JPopupMenu popup = new JPopupMenu();
popup.add(new JMenuItem("item one"));
popup.add(new JMenuItem("item two"));
popup.add(new JMenuItem("item three"));
popup.add(new JMenuItem("item four"));
popup.add(new JMenuItem("item five"));
contentPane.add(label,BorderLayout.CENTER);
label.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
popup.show(label,e.getX(),e.getY());
}
});
setTitle("Popup Menu");
setSize(500,400);
}
public static void main(String[] args)
{
JFrame frame = new PopupDemo();
frame.setVisible(true);
}
}
import java.awt.event.*;
import javax.swing.*;
public class PopupDemo extends JFrame
{
public PopupDemo()
{
Container contentPane = getContentPane();
final JLabel label = new JLabel("Click here");
label.setHorizontalAlignment(JLabel.CENTER);
final JPopupMenu popup = new JPopupMenu();
popup.add(new JMenuItem("item one"));
popup.add(new JMenuItem("item two"));
popup.add(new JMenuItem("item three"));
popup.add(new JMenuItem("item four"));
popup.add(new JMenuItem("item five"));
contentPane.add(label,BorderLayout.CENTER);
label.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
popup.show(label,e.getX(),e.getY());
}
});
setTitle("Popup Menu");
setSize(500,400);
}
public static void main(String[] args)
{
JFrame frame = new PopupDemo();
frame.setVisible(true);
}
}
|
你用
JPopupMenu pm = new JPopupMenu();
pm.add(new JMenuItem("haha"));
pm.show(e.getComponent(),e.getX(),e.getY());
这个就没有问题了。
JPopupMenu pm = new JPopupMenu();
pm.add(new JMenuItem("haha"));
pm.show(e.getComponent(),e.getX(),e.getY());
这个就没有问题了。
|
PopupMenu pm = new PopupMenu();
popup.show(e.getComponent(), e.getX(), e.getY());
popup.show(e.getComponent(), e.getX(), e.getY());