Source code: org/altara/util/KeyActionSupport.java
1 /* Altara Utility Classes
2 Copyright (C) 2001,2002 Brian H. Trammell
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with this library; if not, it is available at
16 http://www.gnu.org/copyleft/lesser.html, or by writing to the
17 Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 Boston, MA 02111-1307 USA
19 */
20
21 package org.altara.util;
22
23 import java.util.*;
24 import java.awt.*;
25 import java.awt.event.*;
26 import javax.swing.*;
27 import javax.swing.event.*;
28
29 public class KeyActionSupport extends KeyAdapter {
30
31 private HashMap keyActions;
32
33 public KeyActionSupport() {
34 this.keyActions = new HashMap();
35 }
36
37 public void addKeyAction(int keyCode, int modifiers, Action action) {
38 ModKey mk = new ModKey(keyCode,modifiers);
39 keyActions.put(mk, action);
40 }
41
42 public void addCommandKey(int keyCode, Action action) {
43 addKeyAction(keyCode,KeyEvent.CTRL_MASK,action);
44 addKeyAction(keyCode,KeyEvent.META_MASK,action);
45 }
46
47 public void keyReleased(KeyEvent ke) {
48 ModKey mk = new ModKey(ke);
49 Action action = (Action)keyActions.get(mk);
50 if (action != null && action.isEnabled()) {
51 action.actionPerformed(
52 new ActionEvent(ke.getSource(),0,"KeyTyped"));
53 }
54 }
55
56 private static class ModKey {
57 int code;
58 int mod;
59
60 private ModKey(int code, int mod) {
61 this.code = code;
62 this.mod = mod;
63 }
64
65 private ModKey(KeyEvent ke) {
66 this.code = ke.getKeyCode();
67 this.mod = ke.getModifiers();
68 }
69
70 public String toString() {
71 return "["+code+","+mod+"]";
72 }
73
74 public boolean equals(Object o) {
75 if (o instanceof ModKey) {
76 ModKey mko = (ModKey)o;
77 return mko.code == code && mko.mod == mod;
78 } else {
79 return false;
80 }
81 }
82
83 public int hashCode() {
84 return (mod << 8) + code;
85 }
86 }
87 }