JPopupMenu弹出式菜单例子

package Assis;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PopupMenuDemo extends JFrame {
	
	private static final long serialVersionUID = 1L;

	public PopupMenuDemo(String strTitle) {
		// 设置框架窗体标题
		super(strTitle);

		// 创建弹出式菜单
		final JPopupMenu mnuRoot = new JPopupMenu();
		mnuRoot.add(new JMenuItem("新建", new ImageIcon("new.gif")));
		mnuRoot.add(new JMenuItem("保存", new ImageIcon("save.gif")));
		mnuRoot.add(new JMenuItem("打印", new ImageIcon("print.gif")));

		final JLabel label = new JLabel("单击我来噢", JLabel.CENTER);
		label.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				mnuRoot.show(label, e.getX(), e.getY());
			}
		});

		this.getContentPane().add(label);
	}

	// 设置框架窗体的大小为宽400,高为400
	public Dimension getPreferredSize() {
		return new Dimension(400, 400);
	}

	// 程序的入口方法
	public static void main(String[] args) {
		// 创建框架窗体
		PopupMenuDemo frame = new PopupMenuDemo("这是个使用弹出式菜单的例子");

		// 设置框架窗体的事件监听(关闭窗体事件)
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		// 显示框架窗体
		frame.pack();
		frame.setVisible(true);

	}
}

 

你可能感兴趣的:(框架,swing)