Java JPopupMenu

1 Java JPopupMenu的介绍

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

2 Java JPopupMenu的声明

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

public class JPopupMenu extends JComponent implements Accessible, MenuElement  

3 Java JPopupMenu的构造方法

方法 描述
JPopupMenu() 构造一个不带“调用程序”的JPopupMenu。
JPopupMenu(String label) 构造具有指定标题的JPopupMenu。

4 Java JPopupMenu的案例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */

import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample
{
    PopupMenuExample(){
        final JFrame f= new JFrame("JPopupMenu案例-一点教程网");
        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();
    }
}

输出结果为:

5 Java JPopupMenu的案例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */

import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample
{
    PopupMenuExample(){
        final JFrame f= new JFrame("JPopupMenu案例-一点教程网");
        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();
    }
}

输出结果为:

热门文章

优秀文章