📜  Java Swing-JPopupMenu

📅  最后修改于: 2020-09-30 06:02:16             🧑  作者: Mango

Java JPopupMenu

PopupMenu可以在组件内的特定位置动态弹出。它继承了JComponent类。

JPopupMenu类声明

我们来看一下javax.swing.JPopupMenu类的声明。

public class JPopupMenu extends JComponent implements Accessible, MenuElement

常用的构造函数:

Constructor Description
JPopupMenu() Constructs a JPopupMenu without an “invoker”.
JPopupMenu(String label) Constructs a JPopupMenu with the specified title.

Java JPopupMenu示例

import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample
{
 PopupMenuExample(){
         final JFrame f= new JFrame("PopupMenu Example");
         final JPopupMenu popupmenu = new JPopupMenu("Edit"); 
         JMenuItem cut = new JMenuItem("Cut");
         JMenuItem copy = new JMenuItem("Copy");
         JMenuItem paste = new JMenuItem("Paste");
         popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);      
         f.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {            
            popupmenu.show(f , e.getX(), e.getY());
            }               
         });
         f.add(popupmenu); 
         f.setSize(300,300);
         f.setLayout(null);
         f.setVisible(true);
 }
public static void main(String args[])
{
        new PopupMenuExample();
}}

输出:

带有MouseListener和ActionListener的Java JPopupMenu示例

import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample 
{
 PopupMenuExample(){
         final JFrame f= new JFrame("PopupMenu Example");
         final JLabel label = new JLabel();        
         label.setHorizontalAlignment(JLabel.CENTER);
         label.setSize(400,100);
         final JPopupMenu popupmenu = new JPopupMenu("Edit"); 
         JMenuItem cut = new JMenuItem("Cut");
         JMenuItem copy = new JMenuItem("Copy");
         JMenuItem paste = new JMenuItem("Paste");
         popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);      
         f.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {            
            popupmenu.show(f , e.getX(), e.getY());
            }               
         });
        cut.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e) {            
             label.setText("cut MenuItem clicked.");
         }
        });
        copy.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {            
                label.setText("copy MenuItem clicked.");
            }
           });
        paste.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {            
                label.setText("paste MenuItem clicked.");
            }
           });
         f.add(label); f.add(popupmenu); 
         f.setSize(400,400);
         f.setLayout(null);
         f.setVisible(true);
 }
public static void main(String args[])
{
        new PopupMenuExample();
}
}

输出: