今天一同学问我,他做桌面系统的时候想使用热键,如何使用!事实上JDK给我们提供了几种简单的复合键的应用(参考InputEvent类)alt+、ctrl+,不过这种复合键明显有局限性!若是用户想自定义热键,JDK提供给我们的就无法实现了!于是我就自己做了一个复合键监听器。
代码如下所示:
实际上监听器只是有这么一个作用而已,当键盘被按下时,监听器会将按下的keycode值保存到集合中,键盘被释放时,该keycode被移除!同时也保证了集合中的keycode不重复和顺序!
如何使用该监听器?主函数里头有!
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);
}
}