JMenuItem的事件处理:



由于JMenuItem继承AbstractButton类,因此JMenuItem也具备了许多AbstractButton的特性,当然也包含了事件处理的机制. JMenuItem的事件处理机制是类似JButton的事件处理模式,换名话说,当按下JMenuItem组件时就如同按下JButton组件一般,均会产生 ActionEvent事件,我们来看下面这一范例:

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

public class JMenuItem5 extends JFrame {
	JTextArea theArea = null;

	public JMenuItem5() {
		super("JMenuItem5");
		theArea = new JTextArea();
		theArea.setEditable(false);
		getContentPane().add(new JScrollPane(theArea));
		JMenuBar MBar = new JMenuBar();
		MBar.setOpaque(true);

		JMenu mfile = buildFileMenu();
		MBar.add(mfile);
		setJMenuBar(MBar);
	}

	public JMenu buildFileMenu() {

		JMenu thefile = new JMenu("File");
		thefile.setMnemonic('F');

		JMenuItem newf = new JMenuItem("New", new ImageIcon("icons/new24.gif"));
		JMenuItem open = new JMenuItem("Open",
				new ImageIcon("icons/open24.gif"));
		JMenuItem close = new JMenuItem("Close", new ImageIcon(
				"icons/close24.gif"));
		JMenuItem quit = new JMenuItem("Exit",
				new ImageIcon("icons/exit24.gif"));

		newf.setMnemonic('N');
		open.setMnemonic('O');
		close.setMnemonic('L');
		quit.setMnemonic('X');

		newf.setAccelerator(KeyStroke.getKeyStroke('N',
				java.awt.Event.CTRL_MASK, false));
		open.setAccelerator(KeyStroke.getKeyStroke('O',
				java.awt.Event.CTRL_MASK, false));
		close.setAccelerator(KeyStroke.getKeyStroke('L',
				java.awt.Event.CTRL_MASK, false));
		quit.setAccelerator(KeyStroke.getKeyStroke('X',
				java.awt.Event.CTRL_MASK, false));

		newf.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				theArea.append("- MenuItem New Performed -\n");
			}
		});

		open.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				theArea.append("- MenuItem Open Performed -\n");
			}
		});

		close.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				theArea.append("- MenuItem Close Performed -\n");
			}
		});

		quit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});

		thefile.add(newf);
		thefile.add(open);
		thefile.add(close);
		thefile.addSeparator();
		thefile.add(quit);

		return thefile;
	}// end of buildFileMenu()

	public static void main(String[] args) {

		JFrame F = new JMenuItem5();
		F.setSize(400, 200);
		F.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});// end of addWindowListener
		F.setVisible(true);
	} // end of main
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值