下面列出了java.awt.event.KeyEvent#KEY_TYPED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns an <code>AWTKeyStroke</code> which represents the
* stroke which generated a given <code>KeyEvent</code>.
* <p>
* This method obtains the keyChar from a <code>KeyTyped</code>
* event, and the keyCode from a <code>KeyPressed</code> or
* <code>KeyReleased</code> event. The <code>KeyEvent</code> modifiers are
* obtained for all three types of <code>KeyEvent</code>.
*
* @param anEvent the <code>KeyEvent</code> from which to
* obtain the <code>AWTKeyStroke</code>
* @throws NullPointerException if <code>anEvent</code> is null
* @return the <code>AWTKeyStroke</code> that precipitated the event
*/
public static AWTKeyStroke getAWTKeyStrokeForEvent(KeyEvent anEvent) {
int id = anEvent.getID();
switch(id) {
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED:
return getCachedStroke(KeyEvent.CHAR_UNDEFINED,
anEvent.getKeyCode(),
anEvent.getModifiers(),
(id == KeyEvent.KEY_RELEASED));
case KeyEvent.KEY_TYPED:
return getCachedStroke(anEvent.getKeyChar(),
KeyEvent.VK_UNDEFINED,
anEvent.getModifiers(),
false);
default:
// Invalid ID for this KeyEvent
return null;
}
}
private void dispatchKeyEvent(final Component component, JavaAgentKeys keyToPress, int id, char c) {
try {
Rectangle d = EventQueueWait.exec(new Callable<Rectangle>() {
@Override
public Rectangle call() {
return component.getBounds();
}
});
ensureVisible(component.getParent(), d);
EventQueueWait.call_noexc(component, "requestFocusInWindow");
} catch (Exception e) {
throw new RuntimeException("getBounds failed for " + component.getClass().getName(), e);
}
final KeysMap keysMap = KeysMap.findMap(keyToPress);
if (keysMap == null) {
return;
}
int m = deviceState.getModifierEx();
int keyCode = keysMap.getCode();
if (id == KeyEvent.KEY_TYPED) {
keyCode = KeyEvent.VK_UNDEFINED;
}
dispatchEvent(new KeyEvent(component, id, System.currentTimeMillis(), m, keyCode, c));
EventQueueWait.empty();
}
/**
* Returns an {@code AWTKeyStroke} which represents the
* stroke which generated a given {@code KeyEvent}.
* <p>
* This method obtains the keyChar from a {@code KeyTyped}
* event, and the keyCode from a {@code KeyPressed} or
* {@code KeyReleased} event. The {@code KeyEvent} modifiers are
* obtained for all three types of {@code KeyEvent}.
*
* @param anEvent the {@code KeyEvent} from which to
* obtain the {@code AWTKeyStroke}
* @throws NullPointerException if {@code anEvent} is null
* @return the {@code AWTKeyStroke} that precipitated the event
*/
@SuppressWarnings("deprecation")
public static AWTKeyStroke getAWTKeyStrokeForEvent(KeyEvent anEvent) {
int id = anEvent.getID();
switch(id) {
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED:
return getCachedStroke(KeyEvent.CHAR_UNDEFINED,
anEvent.getKeyCode(),
anEvent.getModifiers(),
(id == KeyEvent.KEY_RELEASED));
case KeyEvent.KEY_TYPED:
return getCachedStroke(anEvent.getKeyChar(),
KeyEvent.VK_UNDEFINED,
anEvent.getModifiers(),
false);
default:
// Invalid ID for this KeyEvent
return null;
}
}
/**
* Returns an <code>AWTKeyStroke</code> which represents the
* stroke which generated a given <code>KeyEvent</code>.
* <p>
* This method obtains the keyChar from a <code>KeyTyped</code>
* event, and the keyCode from a <code>KeyPressed</code> or
* <code>KeyReleased</code> event. The <code>KeyEvent</code> modifiers are
* obtained for all three types of <code>KeyEvent</code>.
*
* @param anEvent the <code>KeyEvent</code> from which to
* obtain the <code>AWTKeyStroke</code>
* @throws NullPointerException if <code>anEvent</code> is null
* @return the <code>AWTKeyStroke</code> that precipitated the event
*/
public static AWTKeyStroke getAWTKeyStrokeForEvent(KeyEvent anEvent) {
int id = anEvent.getID();
switch(id) {
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED:
return getCachedStroke(KeyEvent.CHAR_UNDEFINED,
anEvent.getKeyCode(),
anEvent.getModifiers(),
(id == KeyEvent.KEY_RELEASED));
case KeyEvent.KEY_TYPED:
return getCachedStroke(anEvent.getKeyChar(),
KeyEvent.VK_UNDEFINED,
anEvent.getModifiers(),
false);
default:
// Invalid ID for this KeyEvent
return null;
}
}
/**
* Returns the type of <code>KeyEvent</code> which corresponds to
* this <code>AWTKeyStroke</code>.
*
* @return <code>KeyEvent.KEY_PRESSED</code>,
* <code>KeyEvent.KEY_TYPED</code>,
* or <code>KeyEvent.KEY_RELEASED</code>
* @see java.awt.event.KeyEvent
*/
public final int getKeyEventType() {
if (keyCode == KeyEvent.VK_UNDEFINED) {
return KeyEvent.KEY_TYPED;
} else {
return (onKeyRelease)
? KeyEvent.KEY_RELEASED
: KeyEvent.KEY_PRESSED;
}
}
private void pressKey()
{
KeyEvent keyPress = new KeyEvent(this.client.getCanvas(), KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_BACK_SPACE);
this.client.getCanvas().dispatchEvent(keyPress);
KeyEvent keyRelease = new KeyEvent(this.client.getCanvas(), KeyEvent.KEY_RELEASED, System.currentTimeMillis(), 0, KeyEvent.VK_BACK_SPACE);
this.client.getCanvas().dispatchEvent(keyRelease);
KeyEvent keyTyped = new KeyEvent(this.client.getCanvas(), KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_BACK_SPACE);
this.client.getCanvas().dispatchEvent(keyTyped);
}
/**
* Returns the type of <code>KeyEvent</code> which corresponds to
* this <code>AWTKeyStroke</code>.
*
* @return <code>KeyEvent.KEY_PRESSED</code>,
* <code>KeyEvent.KEY_TYPED</code>,
* or <code>KeyEvent.KEY_RELEASED</code>
* @see java.awt.event.KeyEvent
*/
public final int getKeyEventType() {
if (keyCode == KeyEvent.VK_UNDEFINED) {
return KeyEvent.KEY_TYPED;
} else {
return (onKeyRelease)
? KeyEvent.KEY_RELEASED
: KeyEvent.KEY_PRESSED;
}
}
public void processKeyEvent(@Nonnull KeyEvent e) {
if (e.isConsumed()) return;
if (e.getID() != KeyEvent.KEY_TYPED) return;
if (!StringUtil.isEmptyOrSpaces(myPopup.getSpeedSearch().getFilter())) return;
if (Character.isLetterOrDigit(e.getKeyChar())) {
final String s = Character.toString(e.getKeyChar());
final T toSelect = myChar2ValueMap.get(s);
if (toSelect != null) {
select(toSelect);
e.consume();
}
}
}
public void testGlobalActionDoesNotSurviveFocusChange() throws Exception {
myGlobalAction.setEnabled( true );
final org.openide.nodes.Node n = new org.openide.nodes.AbstractNode (org.openide.nodes.Children.LEAF);
tc.setActivatedNodes(new Node[0]);
KeyEvent e = new KeyEvent( tc, KeyEvent.KEY_TYPED, 0, 0, 0 );
assertTrue( tc.processKeyBinding( KEY_STROKE, e, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, true ) );
assertTrue( MyContextAwareAction.globalActionWasPerformed );
assertFalse( MyContextAwareAction.contextActionWasPerformed );
}
@Override
@SuppressWarnings("deprecation")
public boolean handleJavaKeyEvent(KeyEvent e) {
switch (e.getID()) {
case KeyEvent.KEY_TYPED:
if ((e.getKeyChar() == '\n') && !e.isAltDown() && !e.isControlDown()) {
postEvent(new ActionEvent(target, ActionEvent.ACTION_PERFORMED,
getText(), e.getWhen(), e.getModifiers()));
return true;
}
break;
}
return false;
}
private boolean consumeProcessedKeyEvent(KeyEvent e) {
if ((e.getID() == KeyEvent.KEY_TYPED) && consumeNextKeyTyped) {
e.consume();
consumeNextKeyTyped = false;
return true;
}
return false;
}
/**
* Returns the type of <code>KeyEvent</code> which corresponds to
* this <code>AWTKeyStroke</code>.
*
* @return <code>KeyEvent.KEY_PRESSED</code>,
* <code>KeyEvent.KEY_TYPED</code>,
* or <code>KeyEvent.KEY_RELEASED</code>
* @see java.awt.event.KeyEvent
*/
public final int getKeyEventType() {
if (keyCode == KeyEvent.VK_UNDEFINED) {
return KeyEvent.KEY_TYPED;
} else {
return (onKeyRelease)
? KeyEvent.KEY_RELEASED
: KeyEvent.KEY_PRESSED;
}
}
public void processEvent(AWTEvent event) {
setIndexOfType(super.getIndexOfType());
if (event instanceof MouseEvent) {
MouseEvent me = (MouseEvent) event;
switch (me.getID()) {
case MouseEvent.MOUSE_ENTERED:
mouseEntered(me);
break;
case MouseEvent.MOUSE_PRESSED:
mousePressed(me);
break;
case MouseEvent.MOUSE_RELEASED:
mouseReleased(me);
break;
case MouseEvent.MOUSE_CLICKED:
mouseClicked(me);
break;
case MouseEvent.MOUSE_EXITED:
mouseExited(me);
break;
}
} else if (event instanceof KeyEvent) {
KeyEvent ke = (KeyEvent) event;
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
keyPressed(ke);
break;
case KeyEvent.KEY_RELEASED:
keyReleased(ke);
break;
case KeyEvent.KEY_TYPED:
keyTyped(ke);
break;
}
}
}
/**
* This method initiates a focus traversal operation if and only if the
* KeyEvent represents a focus traversal key for the specified
* focusedComponent. It is expected that focusedComponent is the current
* focus owner, although this need not be the case. If it is not,
* focus traversal will nevertheless proceed as if focusedComponent
* were the focus owner.
*
* @param focusedComponent the Component that is the basis for a focus
* traversal operation if the specified event represents a focus
* traversal key for the Component
* @param e the event that may represent a focus traversal key
*/
public void processKeyEvent(Component focusedComponent, KeyEvent e) {
// consume processed event if needed
if (consumeProcessedKeyEvent(e)) {
return;
}
// KEY_TYPED events cannot be focus traversal keys
if (e.getID() == KeyEvent.KEY_TYPED) {
return;
}
if (focusedComponent.getFocusTraversalKeysEnabled() &&
!e.isConsumed())
{
AWTKeyStroke stroke = AWTKeyStroke.getAWTKeyStrokeForEvent(e),
oppStroke = AWTKeyStroke.getAWTKeyStroke(stroke.getKeyCode(),
stroke.getModifiers(),
!stroke.isOnKeyRelease());
Set<AWTKeyStroke> toTest;
boolean contains, containsOpp;
toTest = focusedComponent.getFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
contains = toTest.contains(stroke);
containsOpp = toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
focusNextComponent(focusedComponent);
}
return;
} else if (e.getID() == KeyEvent.KEY_PRESSED) {
// Fix for 6637607: consumeNextKeyTyped should be reset.
consumeNextKeyTyped = false;
}
toTest = focusedComponent.getFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
contains = toTest.contains(stroke);
containsOpp = toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
focusPreviousComponent(focusedComponent);
}
return;
}
toTest = focusedComponent.getFocusTraversalKeys(
KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS);
contains = toTest.contains(stroke);
containsOpp = toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
upFocusCycle(focusedComponent);
}
return;
}
if (!((focusedComponent instanceof Container) &&
((Container)focusedComponent).isFocusCycleRoot())) {
return;
}
toTest = focusedComponent.getFocusTraversalKeys(
KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS);
contains = toTest.contains(stroke);
containsOpp = toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
downFocusCycle((Container)focusedComponent);
}
}
}
}
public void testSelection4() throws Exception {
KeyEvent ke = new KeyEvent(new JFrame(), KeyEvent.KEY_TYPED, 0, 0, KeyEvent.VK_UNDEFINED, 'a');
performTest("package test; public class Test { public void test() {int x|xx = 0; int y = xxx; } }", 79 - 22, ke, 83 - 22 - 1, "package test; public class Test { public void test() {intax = 0; int y = xxx; } }", false);
}
/**
* Dispatches committed text to a client component.
* Called by composition window.
*
* @param client The component that the text should get dispatched to.
* @param text The iterator providing access to the committed
* (and possible composed) text.
* @param committedCharacterCount The number of committed characters in the text.
*/
synchronized void dispatchCommittedText(Component client,
AttributedCharacterIterator text,
int committedCharacterCount) {
// note that the client is not always the current client component -
// some host input method adapters may dispatch input method events
// through the Java event queue, and we may have switched clients while
// the event was in the queue.
if (committedCharacterCount == 0
|| text.getEndIndex() <= text.getBeginIndex()) {
return;
}
long time = System.currentTimeMillis();
dispatchingCommittedText = true;
try {
InputMethodRequests req = client.getInputMethodRequests();
if (req != null) {
// active client -> send text as InputMethodEvent
int beginIndex = text.getBeginIndex();
AttributedCharacterIterator toBeCommitted =
(new AttributedString(text, beginIndex, beginIndex + committedCharacterCount)).getIterator();
InputMethodEvent inputEvent = new InputMethodEvent(
client,
InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
toBeCommitted,
committedCharacterCount,
null, null);
client.dispatchEvent(inputEvent);
} else {
// passive client -> send text as KeyEvents
char keyChar = text.first();
while (committedCharacterCount-- > 0 && keyChar != CharacterIterator.DONE) {
KeyEvent keyEvent = new KeyEvent(client, KeyEvent.KEY_TYPED,
time, 0, KeyEvent.VK_UNDEFINED, keyChar);
client.dispatchEvent(keyEvent);
keyChar = text.next();
}
}
} finally {
dispatchingCommittedText = false;
}
}
private boolean typeAheadAssertions(Component target, AWTEvent e) {
// Clear any pending events here as well as in the FOCUS_GAINED
// handler. We need this call here in case a marker was removed in
// response to a call to dequeueKeyEvents.
pumpApprovedKeyEvents();
switch (e.getID()) {
case KeyEvent.KEY_TYPED:
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED: {
KeyEvent ke = (KeyEvent)e;
synchronized (this) {
if (e.isPosted && typeAheadMarkers.size() != 0) {
TypeAheadMarker marker = typeAheadMarkers.getFirst();
// Fixed 5064013: may appears that the events have the same time
// if (ke.getWhen() >= marker.after) {
// The fix is rolled out.
if (ke.getWhen() > marker.after) {
if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
focusLog.finer("Storing event {0} because of marker {1}", ke, marker);
}
enqueuedKeyEvents.addLast(ke);
return true;
}
}
}
// KeyEvent was posted before focus change request
return preDispatchKeyEvent(ke);
}
case FocusEvent.FOCUS_GAINED:
if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
focusLog.finest("Markers before FOCUS_GAINED on {0}", target);
}
dumpMarkers();
// Search the marker list for the first marker tied to
// the Component which just gained focus. Then remove
// that marker, any markers which immediately follow
// and are tied to the same component, and all markers
// that precede it. This handles the case where
// multiple focus requests were made for the same
// Component in a row and when we lost some of the
// earlier requests. Since FOCUS_GAINED events will
// not be generated for these additional requests, we
// need to clear those markers too.
synchronized (this) {
boolean found = false;
if (hasMarker(target)) {
for (Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator();
iter.hasNext(); )
{
if (iter.next().untilFocused == target) {
found = true;
} else if (found) {
break;
}
iter.remove();
}
} else {
// Exception condition - event without marker
if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
focusLog.finer("Event without marker {0}", e);
}
}
}
focusLog.finest("Markers after FOCUS_GAINED");
dumpMarkers();
redispatchEvent(target, e);
// Now, dispatch any pending KeyEvents which have been
// released because of the FOCUS_GAINED event so that we don't
// have to wait for another event to be posted to the queue.
pumpApprovedKeyEvents();
return true;
default:
redispatchEvent(target, e);
return true;
}
}
protected @Override boolean processKeyBinding(KeyStroke ks,
KeyEvent e,
int condition,
boolean pressed) {
if (Utilities.isMac()) {
int mods = e.getModifiers();
boolean isCtrl = (mods & KeyEvent.CTRL_MASK) != 0;
boolean isAlt = (mods & KeyEvent.ALT_MASK) != 0;
if (isAlt && (e instanceof MarkedKeyEvent)) {
mods = mods & ~ KeyEvent.CTRL_MASK;
mods = mods & ~ KeyEvent.CTRL_DOWN_MASK;
mods |= KeyEvent.ALT_MASK;
mods |= KeyEvent.ALT_DOWN_MASK;
KeyEvent newEvent = new MarkedKeyEvent (
(Component) e.getSource(), e.getID(),
e.getWhen(), mods, e.getKeyCode(), e.getKeyChar(),
e.getKeyLocation());
KeyStroke newStroke = null;
if( null != ks ) {
newStroke = e.getID() == KeyEvent.KEY_TYPED ?
KeyStroke.getKeyStroke (ks.getKeyChar(), mods) :
KeyStroke.getKeyStroke (ks.getKeyCode(), mods,
!ks.isOnKeyRelease());
}
boolean result = super.processKeyBinding (newStroke,
newEvent, condition, pressed);
if (newEvent.isConsumed()) {
e.consume();
}
return result;
} else if (!isAlt) {
return super.processKeyBinding (ks, e, condition, pressed);
} else {
return false;
}
} else {
return super.processKeyBinding (ks, e, condition, pressed);
}
}
/**
* Dispatches committed text to a client component.
* Called by composition window.
*
* @param client The component that the text should get dispatched to.
* @param text The iterator providing access to the committed
* (and possible composed) text.
* @param committedCharacterCount The number of committed characters in the text.
*/
synchronized void dispatchCommittedText(Component client,
AttributedCharacterIterator text,
int committedCharacterCount) {
// note that the client is not always the current client component -
// some host input method adapters may dispatch input method events
// through the Java event queue, and we may have switched clients while
// the event was in the queue.
if (committedCharacterCount == 0
|| text.getEndIndex() <= text.getBeginIndex()) {
return;
}
long time = System.currentTimeMillis();
dispatchingCommittedText = true;
try {
InputMethodRequests req = client.getInputMethodRequests();
if (req != null) {
// active client -> send text as InputMethodEvent
int beginIndex = text.getBeginIndex();
AttributedCharacterIterator toBeCommitted =
(new AttributedString(text, beginIndex, beginIndex + committedCharacterCount)).getIterator();
InputMethodEvent inputEvent = new InputMethodEvent(
client,
InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
toBeCommitted,
committedCharacterCount,
null, null);
client.dispatchEvent(inputEvent);
} else {
// passive client -> send text as KeyEvents
char keyChar = text.first();
while (committedCharacterCount-- > 0 && keyChar != CharacterIterator.DONE) {
KeyEvent keyEvent = new KeyEvent(client, KeyEvent.KEY_TYPED,
time, 0, KeyEvent.VK_UNDEFINED, keyChar);
client.dispatchEvent(keyEvent);
keyChar = text.next();
}
}
} finally {
dispatchingCommittedText = false;
}
}
private boolean typeAheadAssertions(Component target, AWTEvent e) {
// Clear any pending events here as well as in the FOCUS_GAINED
// handler. We need this call here in case a marker was removed in
// response to a call to dequeueKeyEvents.
pumpApprovedKeyEvents();
switch (e.getID()) {
case KeyEvent.KEY_TYPED:
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED: {
KeyEvent ke = (KeyEvent)e;
synchronized (this) {
if (e.isPosted && typeAheadMarkers.size() != 0) {
TypeAheadMarker marker = typeAheadMarkers.getFirst();
// Fixed 5064013: may appears that the events have the same time
// if (ke.getWhen() >= marker.after) {
// The fix is rolled out.
if (ke.getWhen() > marker.after) {
if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
focusLog.finer("Storing event {0} because of marker {1}", ke, marker);
}
enqueuedKeyEvents.addLast(ke);
return true;
}
}
}
// KeyEvent was posted before focus change request
return preDispatchKeyEvent(ke);
}
case FocusEvent.FOCUS_GAINED:
if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
focusLog.finest("Markers before FOCUS_GAINED on {0}", target);
}
dumpMarkers();
// Search the marker list for the first marker tied to
// the Component which just gained focus. Then remove
// that marker, any markers which immediately follow
// and are tied to the same component, and all markers
// that preceed it. This handles the case where
// multiple focus requests were made for the same
// Component in a row and when we lost some of the
// earlier requests. Since FOCUS_GAINED events will
// not be generated for these additional requests, we
// need to clear those markers too.
synchronized (this) {
boolean found = false;
if (hasMarker(target)) {
for (Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator();
iter.hasNext(); )
{
if (iter.next().untilFocused == target) {
found = true;
} else if (found) {
break;
}
iter.remove();
}
} else {
// Exception condition - event without marker
if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
focusLog.finer("Event without marker {0}", e);
}
}
}
focusLog.finest("Markers after FOCUS_GAINED");
dumpMarkers();
redispatchEvent(target, e);
// Now, dispatch any pending KeyEvents which have been
// released because of the FOCUS_GAINED event so that we don't
// have to wait for another event to be posted to the queue.
pumpApprovedKeyEvents();
return true;
default:
redispatchEvent(target, e);
return true;
}
}