下面列出了怎么用java.awt.AWTKeyStroke的API类实例代码及写法,或者点击链接到github查看源代码。
AWTKeyStroke getKeyStrokeForKeySym(long keysym, long state) {
XBaseWindow.checkSecurity();
int keycode;
XToolkit.awtLock();
try {
XKeysym.Keysym2JavaKeycode kc = XKeysym.getJavaKeycode( keysym );
if(kc == null) {
keycode = java.awt.event.KeyEvent.VK_UNDEFINED;
}else{
keycode = kc.getJavaKeycode();
}
} finally {
XToolkit.awtUnlock();
}
int modifiers = getModifiers((int)state);
return AWTKeyStroke.getAWTKeyStroke(keycode, modifiers);
}
public static synchronized void install() {
if(installed) {
return;
}
ShortcutAndMenuKeyEventProcessor instance = getDefault();
KeyboardFocusManager keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
keyboardFocusManager.addKeyEventDispatcher(instance);
keyboardFocusManager.addKeyEventPostProcessor(instance);
// #63252: Disable focus traversal functionality of Ctrl+Tab and Ctrl+Shift+Tab,
// to allow our own document switching (RecentViewListAction)
defaultForward = keyboardFocusManager.getDefaultFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
defaultBackward = keyboardFocusManager.getDefaultFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
keyboardFocusManager.setDefaultFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.singleton(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, 0))
);
keyboardFocusManager.setDefaultFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
Collections.singleton(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK))
);
}
AWTKeyStroke getKeyStrokeForKeySym(long keysym, long state) {
XBaseWindow.checkSecurity();
int keycode;
XToolkit.awtLock();
try {
XKeysym.Keysym2JavaKeycode kc = XKeysym.getJavaKeycode( keysym );
if(kc == null) {
keycode = java.awt.event.KeyEvent.VK_UNDEFINED;
}else{
keycode = kc.getJavaKeycode();
}
} finally {
XToolkit.awtUnlock();
}
int modifiers = getModifiers((int)state);
return AWTKeyStroke.getAWTKeyStroke(keycode, modifiers);
}
public void initialize() {
this.addMouseListener(this);
// this.setFocusTraversalKeysEnabled(false);
this.addKeyListener(this);
this.setFocusable(true);
this.addFocusListener(this);
this.setFocusTraversalKeysEnabled(true);
this.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,new HashSet(new EasyVector(new Object[]{AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,0)})));
this.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,new HashSet(new EasyVector(new Object[]{AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,InputEvent.SHIFT_DOWN_MASK)})));
this.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
// undoManager = new UndoManager();
// Document document = this.getDocument();
// document.addUndoableEditListener(undoManager);
this.setMargin(defaultMargins);
this.setDragEnabled(true);
dt = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
setPopupMenu();
}
private static void checkAWTKeyStroke(int keyCode, int modifiers,
boolean onKeyRelease) throws Exception {
AWTKeyStroke awtKeyStroke1 = AWTKeyStroke.getAWTKeyStroke(
keyCode, modifiers, onKeyRelease);
checkAWTKeyStroke(awtKeyStroke1, keyCode, modifiers, onKeyRelease);
AWTKeyStroke awtKeyStroke2 = AWTKeyStroke.getAWTKeyStroke(
keyCode, modifiers, onKeyRelease);
if (awtKeyStroke1 != awtKeyStroke2) {
throw new RuntimeException("AWTKeyStroke is not cached!");
}
checkSerializedKeyStroke(awtKeyStroke1);
}
AWTKeyStroke getKeyStrokeForKeySym(long keysym, long state) {
XBaseWindow.checkSecurity();
int keycode;
XToolkit.awtLock();
try {
XKeysym.Keysym2JavaKeycode kc = XKeysym.getJavaKeycode( keysym );
if(kc == null) {
keycode = java.awt.event.KeyEvent.VK_UNDEFINED;
}else{
keycode = kc.getJavaKeycode();
}
} finally {
XToolkit.awtUnlock();
}
int modifiers = getModifiers((int)state);
return AWTKeyStroke.getAWTKeyStroke(keycode, modifiers);
}
/**
* Checks the key event is the input method selection key or not.
*/
private boolean checkInputMethodSelectionKey(KeyEvent event) {
if (inputMethodSelectionKey != null) {
AWTKeyStroke aKeyStroke = AWTKeyStroke.getAWTKeyStrokeForEvent(event);
return inputMethodSelectionKey.equals(aKeyStroke);
} else {
return false;
}
}
private AWTKeyStroke getInputMethodSelectionKeyStroke(Preferences root) {
try {
if (root.nodeExists(inputMethodSelectionKeyPath)) {
Preferences node = root.node(inputMethodSelectionKeyPath);
int keyCode = node.getInt(inputMethodSelectionKeyCodeName, KeyEvent.VK_UNDEFINED);
if (keyCode != KeyEvent.VK_UNDEFINED) {
int modifiers = node.getInt(inputMethodSelectionKeyModifiersName, 0);
return AWTKeyStroke.getAWTKeyStroke(keyCode, modifiers);
}
}
} catch (BackingStoreException bse) {
}
return null;
}
private static void checkSerializedKeyStroke(AWTKeyStroke keyStroke)
throws Exception {
if (keyStroke != getSerializedAWTKeyStroke(keyStroke)) {
throw new RuntimeException("New instance is returned during"
+ " serialization!");
}
}
private static void checkAWTKeyStroke(AWTKeyStroke awtKeyStroke,
int keyCode, int modifiers, boolean onKeyRelease) {
if (awtKeyStroke.getKeyCode() != keyCode) {
throw new RuntimeException("Wrong key code!");
}
if (awtKeyStroke.getModifiers() != modifiers) {
throw new RuntimeException("Wrong modifiers!");
}
if (awtKeyStroke.isOnKeyRelease() != onKeyRelease) {
throw new RuntimeException("Wrong on key release!");
}
}
void registerAccelerator(AWTKeyStroke stroke, int id) {
if (active) {
long sym = getX11KeySym(stroke);
long mods = getX11Mods(stroke);
sendMessage(server, XEMBED_REGISTER_ACCELERATOR, id, sym, mods);
}
}
/**
* This method sets the FocusTraversalKeys for a component to be the standard keys.
* Use this on Tables or TextAreas where you want the tab keys to leave the control.
*
* @param component the component that you want to fix tab keys for
*/
public static void fixTabKeys(final JComponent component) {
final Set<AWTKeyStroke> forward = new HashSet<AWTKeyStroke>(
component.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
forward.add(KeyStroke.getKeyStroke("TAB"));
component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forward);
final Set<AWTKeyStroke> backward = new HashSet<AWTKeyStroke>(
component.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
backward.add(KeyStroke.getKeyStroke("shift TAB"));
component.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backward);
}
void registerAccelerator(AWTKeyStroke stroke, int id) {
if (active) {
long sym = getX11KeySym(stroke);
long mods = getX11Mods(stroke);
sendMessage(server, XEMBED_REGISTER_ACCELERATOR, id, sym, mods);
}
}
private AWTKeyStroke getInputMethodSelectionKeyStroke(Preferences root) {
try {
if (root.nodeExists(inputMethodSelectionKeyPath)) {
Preferences node = root.node(inputMethodSelectionKeyPath);
int keyCode = node.getInt(inputMethodSelectionKeyCodeName, KeyEvent.VK_UNDEFINED);
if (keyCode != KeyEvent.VK_UNDEFINED) {
int modifiers = node.getInt(inputMethodSelectionKeyModifiersName, 0);
return AWTKeyStroke.getAWTKeyStroke(keyCode, modifiers);
}
}
} catch (BackingStoreException bse) {
}
return null;
}
private AWTKeyStroke getInputMethodSelectionKeyStroke(Preferences root) {
try {
if (root.nodeExists(inputMethodSelectionKeyPath)) {
Preferences node = root.node(inputMethodSelectionKeyPath);
int keyCode = node.getInt(inputMethodSelectionKeyCodeName, KeyEvent.VK_UNDEFINED);
if (keyCode != KeyEvent.VK_UNDEFINED) {
int modifiers = node.getInt(inputMethodSelectionKeyModifiersName, 0);
return AWTKeyStroke.getAWTKeyStroke(keyCode, modifiers);
}
}
} catch (BackingStoreException bse) {
}
return null;
}
/**
* Checks the key event is the input method selection key or not.
*/
private boolean checkInputMethodSelectionKey(KeyEvent event) {
if (inputMethodSelectionKey != null) {
AWTKeyStroke aKeyStroke = AWTKeyStroke.getAWTKeyStrokeForEvent(event);
return inputMethodSelectionKey.equals(aKeyStroke);
} else {
return false;
}
}
private AWTKeyStroke getInputMethodSelectionKeyStroke(Preferences root) {
try {
if (root.nodeExists(inputMethodSelectionKeyPath)) {
Preferences node = root.node(inputMethodSelectionKeyPath);
int keyCode = node.getInt(inputMethodSelectionKeyCodeName, KeyEvent.VK_UNDEFINED);
if (keyCode != KeyEvent.VK_UNDEFINED) {
int modifiers = node.getInt(inputMethodSelectionKeyModifiersName, 0);
return AWTKeyStroke.getAWTKeyStroke(keyCode, modifiers);
}
}
} catch (BackingStoreException bse) {
}
return null;
}
long getX11KeySym(AWTKeyStroke stroke) {
XToolkit.awtLock();
try {
return XWindow.getKeySymForAWTKeyCode(stroke.getKeyCode());
} finally {
XToolkit.awtUnlock();
}
}
protected Expression instantiate(Object oldInstance, Encoder out) {
AWTKeyStroke key = (AWTKeyStroke) oldInstance;
char ch = key.getKeyChar();
int code = key.getKeyCode();
int mask = key.getModifiers();
boolean onKeyRelease = key.isOnKeyRelease();
Object[] args = null;
if (ch == KeyEvent.CHAR_UNDEFINED) {
args = !onKeyRelease
? new Object[]{code, mask}
: new Object[]{code, mask, onKeyRelease};
} else if (code == KeyEvent.VK_UNDEFINED) {
if (!onKeyRelease) {
args = (mask == 0)
? new Object[]{ch}
: new Object[]{ch, mask};
} else if (mask == 0) {
args = new Object[]{ch, onKeyRelease};
}
}
if (args == null) {
throw new IllegalStateException("Unsupported KeyStroke: " + key);
}
Class<?> type = key.getClass();
String name = type.getName();
// get short name of the class
int index = name.lastIndexOf('.') + 1;
if (index > 0) {
name = name.substring(index);
}
return new Expression( key, type, "get" + name, args );
}
long getX11KeySym(AWTKeyStroke stroke) {
XToolkit.awtLock();
try {
return XWindow.getKeySymForAWTKeyCode(stroke.getKeyCode());
} finally {
XToolkit.awtUnlock();
}
}
@Override
public void unregisterAccelerator(AWTKeyStroke awtks) {
}
@Override
public void registerAccelerator(AWTKeyStroke awtks) {
}
/**
* Need this method to detect when the focus may have chance to leave the
* focus cycle root which is EmbeddedFrame. Mostly, the code here is copied
* from DefaultKeyboardFocusManager.processKeyEvent with some minor
* modifications.
*/
public boolean dispatchKeyEvent(KeyEvent e) {
Container currentRoot = AWTAccessor.getKeyboardFocusManagerAccessor()
.getCurrentFocusCycleRoot();
// if we are not in EmbeddedFrame's cycle, we should not try to leave.
if (this != currentRoot) {
return false;
}
// KEY_TYPED events cannot be focus traversal keys
if (e.getID() == KeyEvent.KEY_TYPED) {
return false;
}
if (!getFocusTraversalKeysEnabled() || e.isConsumed()) {
return false;
}
AWTKeyStroke stroke = AWTKeyStroke.getAWTKeyStrokeForEvent(e);
Set<AWTKeyStroke> toTest;
Component currentFocused = e.getComponent();
toTest = getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
if (toTest.contains(stroke)) {
// 6581899: performance improvement for SortingFocusTraversalPolicy
Component last = getFocusTraversalPolicy().getLastComponent(this);
if (currentFocused == last || last == null) {
if (traverseOut(FORWARD)) {
e.consume();
return true;
}
}
}
toTest = getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
if (toTest.contains(stroke)) {
// 6581899: performance improvement for SortingFocusTraversalPolicy
Component first = getFocusTraversalPolicy().getFirstComponent(this);
if (currentFocused == first || first == null) {
if (traverseOut(BACKWARD)) {
e.consume();
return true;
}
}
}
return false;
}
/**
* Need this method to detect when the focus may have chance to leave the
* focus cycle root which is EmbeddedFrame. Mostly, the code here is copied
* from DefaultKeyboardFocusManager.processKeyEvent with some minor
* modifications.
*/
public boolean dispatchKeyEvent(KeyEvent e) {
Container currentRoot = AWTAccessor.getKeyboardFocusManagerAccessor()
.getCurrentFocusCycleRoot();
// if we are not in EmbeddedFrame's cycle, we should not try to leave.
if (this != currentRoot) {
return false;
}
// KEY_TYPED events cannot be focus traversal keys
if (e.getID() == KeyEvent.KEY_TYPED) {
return false;
}
if (!getFocusTraversalKeysEnabled() || e.isConsumed()) {
return false;
}
AWTKeyStroke stroke = AWTKeyStroke.getAWTKeyStrokeForEvent(e);
Set<AWTKeyStroke> toTest;
Component currentFocused = e.getComponent();
toTest = getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
if (toTest.contains(stroke)) {
// 6581899: performance improvement for SortingFocusTraversalPolicy
Component last = getFocusTraversalPolicy().getLastComponent(this);
if (currentFocused == last || last == null) {
if (traverseOut(FORWARD)) {
e.consume();
return true;
}
}
}
toTest = getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
if (toTest.contains(stroke)) {
// 6581899: performance improvement for SortingFocusTraversalPolicy
Component first = getFocusTraversalPolicy().getFirstComponent(this);
if (currentFocused == first || first == null) {
if (traverseOut(BACKWARD)) {
e.consume();
return true;
}
}
}
return false;
}
/**
* Need this method to detect when the focus may have chance to leave the
* focus cycle root which is EmbeddedFrame. Mostly, the code here is copied
* from DefaultKeyboardFocusManager.processKeyEvent with some minor
* modifications.
*/
public boolean dispatchKeyEvent(KeyEvent e) {
Container currentRoot = AWTAccessor.getKeyboardFocusManagerAccessor()
.getCurrentFocusCycleRoot();
// if we are not in EmbeddedFrame's cycle, we should not try to leave.
if (this != currentRoot) {
return false;
}
// KEY_TYPED events cannot be focus traversal keys
if (e.getID() == KeyEvent.KEY_TYPED) {
return false;
}
if (!getFocusTraversalKeysEnabled() || e.isConsumed()) {
return false;
}
AWTKeyStroke stroke = AWTKeyStroke.getAWTKeyStrokeForEvent(e);
Set<AWTKeyStroke> toTest;
Component currentFocused = e.getComponent();
toTest = getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
if (toTest.contains(stroke)) {
// 6581899: performance improvement for SortingFocusTraversalPolicy
Component last = getFocusTraversalPolicy().getLastComponent(this);
if (currentFocused == last || last == null) {
if (traverseOut(FORWARD)) {
e.consume();
return true;
}
}
}
toTest = getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
if (toTest.contains(stroke)) {
// 6581899: performance improvement for SortingFocusTraversalPolicy
Component first = getFocusTraversalPolicy().getFirstComponent(this);
if (currentFocused == first || first == null) {
if (traverseOut(BACKWARD)) {
e.consume();
return true;
}
}
}
return false;
}
public void start ()
{
setSize (200,200);
setVisible(true);
validate();
JFrame frame = new JFrame("The Frame");
Set ftk = new HashSet();
ftk.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_DOWN, 0));
frame.getContentPane().
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
ftk);
JCheckBox checkbox = new JCheckBox("test");
frame.getContentPane().add(checkbox, BorderLayout.NORTH);
JTextArea textarea = new JTextArea(40, 10);
frame.getContentPane().add(textarea);
frame.pack();
frame.setVisible(true);
Util.waitForIdle(robot);
if (!frame.isActive()) {
throw new RuntimeException("Test Fialed: frame isn't active");
}
// verify if checkbox has focus
if (!checkbox.isFocusOwner()) {
checkbox.requestFocusInWindow();
Util.waitForIdle(robot);
if (!checkbox.isFocusOwner()) {
throw new RuntimeException("Test Failed: checkbox doesn't have focus");
}
}
// press VK_DOWN
robot.keyPress(KeyEvent.VK_DOWN);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.delay(50);
Util.waitForIdle(robot);
// verify if text area has focus
if (!textarea.isFocusOwner()) {
throw new RuntimeException("Test Failed: focus wasn't transfered to text area");
}
// press '1'
robot.keyPress(KeyEvent.VK_1);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_1);
robot.delay(50);
Util.waitForIdle(robot);
// verify if KEY_TYPED arrived
if (!"1".equals(textarea.getText())) {
throw new RuntimeException("Test Failed: text area text is \"" + textarea.getText() + "\", not \"1\"");
}
System.out.println("Test Passed");
}
long getX11Mods(AWTKeyStroke stroke) {
return XWindow.getXModifiers(stroke);
}
protected AWTKeyStroke getObject() {
return AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_A, InputEvent.SHIFT_DOWN_MASK, true);
}
@Override
public void registerAccelerator(AWTKeyStroke awtks) {
}
protected AWTKeyStroke getAnotherObject() {
return AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK);
}