java复合快捷键

import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public abstract class MultiKeyListener implements KeyListener {

	private List<Integer> codeList = new ArrayList<Integer>();
	
	@Override
	public final void keyTyped(KeyEvent e) {
	}

	@Override
	public final void keyPressed(KeyEvent e) {
		int keyCode = e.getKeyCode();
		if(!codeList.contains(keyCode)) {
			codeList.add(keyCode);
		}
		this.onPressed(codeList, e);
	}

	@Override
	public final void keyReleased(KeyEvent e) {
		for(int i = 0, n = codeList.size() ; i < n ; i++) {
			if(e.getKeyCode() == codeList.get(i)) {
				codeList.remove(i);
				break;
			}
		}
	}
	
	protected abstract void onPressed(List<Integer> codeList, KeyEvent event);
	
	public static void main(String[] args) {
		final JFrame frame = new JFrame() {};
		Container c = frame.getContentPane();
		JTextArea area = new JTextArea();
		c.add(area);
		area.addKeyListener(new MultiKeyListener() {
			
			private List<Integer> closeQuick = new ArrayList<Integer>();
			
			{
				closeQuick.add(KeyEvent.VK_ALT);
				closeQuick.add(KeyEvent.VK_A);
				closeQuick.add(KeyEvent.VK_B);
			}
			
			@Override
			protected void onPressed(List<Integer> codeList, KeyEvent event) {
				//实现alt+a+b输出“关闭程序”
				if(codeList.equals(closeQuick)) {
					System.out.println("程序关闭......");
				}
			}
		});
		frame.setVisible(true);
	}
}
说明:支持多种复合键,可以自行添加按键组合,还有KeyEvent没有KeyEvent.VK_CTRL字段,如要添加ctrl,可以获取ctrl的 keycode,然后直接添加到list里面去。 ctrl的keycode是17.

你可能感兴趣的:(java复合快捷键)