swing 右键菜单快捷键

当我们为JTextField 添加右键快捷键时,发现不管用,其实是管用的,不过你的先显示你的菜单,只有当菜单获得了焦点快捷键方有效,但这样就毫无意义了.解决的办法就是将在JTextField上也添加快捷键,下面是一个Demo.

package org.eclipse.ui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

/**
 * @author zero
 * 
 */
public class Swing {

	private JFrame frame;
	private JTextField textField;
	private JPopupMenu popupMenu;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Swing window = new Swing();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public Swing() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		textField = new JTextField();
		frame.getContentPane().add(textField, BorderLayout.CENTER);
		textField.setColumns(10);

		Action delAction = new AbstractAction("Delete") {
			private static final long serialVersionUID = 1L;

			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("---------del------------");
			}
		};
		popupMenu = new JPopupMenu();
		addPopup(textField, popupMenu);

		JMenuItem mntmAdd = new JMenuItem(delAction);
		mntmAdd.setMnemonic('D');
		mntmAdd.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,
				InputEvent.CTRL_MASK));

		fuckAllMenuItems(mntmAdd);
	}

	private void fuckAllMenuItems(JMenuItem... menuItems) {
		for (JMenuItem item : menuItems) {
			popupMenu.add(item);
			Action action = item.getAction();
			Object key = action.getValue(Action.NAME);
			textField.getInputMap().put(item.getAccelerator(), key);
			textField.getActionMap().put(key, action);
		}
	}

	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
}

 

你可能感兴趣的:(swing,swing,右键菜单,快捷键)