{
if(e.getButton() == MouseEvent.BUTTON3)//点击右键
popUpMenu.show(editMenu, e.getX(), e.getY())
//popUpMenu是一个JPopupMenu editMenu是一个JMenu
//e.getX(), e.getY()是获得鼠标点击的坐标 在点击的地方d出一个 editMenu,editMenu中的 内容自己添加
}
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1)//点击鼠标左键
popUpMenu.setVisible(false)//d出菜单消失
}
你可以直接给textarea添加一个右键监听,当检测到右键事件后,显示一个d出菜单,d出菜单就是自己的顶一定义的功能了。public class PopupMenu extends JFrame {
private JPopupMenu menu
private JTextArea text
public PopupMenu() {
JMenuItem m
MenuItemListener mil = new MenuItemListener()
menu = new JPopupMenu()
text = new JTextArea(15, 30)
m = new JMenuItem("Item1")
m.addActionListener(mil)
menu.add(m)
m = new JMenuItem("Item2")
m.addActionListener(mil)
menu.add(m)
m = new JMenuItem("Item3")
m.addActionListener(mil)
menu.add(m)
text.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
menu.show(text, e.getX(), e.getY())
}
}
})
getContentPane().add(text)
}
private class MenuItemListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
text.setText(((JMenuItem) e.getSource()).getText())
}
}
public static void main(String[] args) {
PopupMenu frame = new PopupMenu()
frame.pack()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setVisible(true)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)