Java key event test script

Keyboard Event Viewer

Interactive tool to test and track any keyboard input event.

Javascript Key Event Test Script

Enter characters in the text box below to see the triggered Javascript events and the values returned. Keypress events are tested in JavaScript. All keyup, keydown, and modifier key events are possible inclusions in this test.

KeyboardEvent

Each event in a KeyboardEvent object specifies a specific interaction between the user and a key (or a key in combination with a set of modifier keys) on the keyboard. The event type (keydown, keypress, or keyup) determines what kind of keyboard activity.

Note that KeyboardEvent events don’t include context for user interactions with keyboard keys; they reveal what those interactions were at a low level. Use the input method whenever you have to deal with text.

How to determine which key is being pressed on a keyboard

When troubleshooting keyboard issues, you may need to check whether the computer recognizes the keys being pressed on the keyboard.

KeyboadEvent Properties

Proprty/Method Description Deprecated/Outdated
altKey Returns a boolean(true/false). The value is true when Alt key is pressed. No
ctrlKey Returns a boolean(true/false). The value is true when Control key is pressed. No
shiftKey Returns a boolean(true/false). The value is true when Shift key is pressed. No
metaKey Returns a boolean(true/false). The value is true when any of the Meta keys are pressed. No
code Code value of the Physical Key. No
key The actual value of the key pressed. No
getModifierState() method Returns a boolean(true/false). The value true indicates the on state of these keys, CapsLock , NumLock , Alt , Control , Shift , Meta , etc. No
charCode Returns the Unicode value. This has been deprecated and we should use the key property instead. Yes
keyCode Returns the neumeric code of the pressed value. This has been deprecated and we should use the key property instead. Yes
which Returns the neumeric code of the pressed value. This has been deprecated and we should use the key property instead. Yes
Читайте также:  font-style

Full List of Key Event Values

Key Name event.which event.key event.code Notes
backspace 8 Backspace Backspace
tab 9 Tab Tab
enter 13 Enter Enter
shift(left) 16 Shift ShiftLeft event.shiftKey is true
shift(right) 16 Shift ShiftRight event.shiftKey is true
ctrl(left) 17 Control ControlLeft event.ctrlKey is true
ctrl(right) 17 Control ControlRight event.ctrlKey is true
alt(left) 18 Alt AltLeft event.altKey is true
alt(right) 18 Alt AltRight event.altKey is true
pause/break 19 Pause Pause
caps lock 20 CapsLock CapsLock
escape 27 Escape Escape
space 32 Space The event.key value is a single space.
page up 33 PageUp PageUp
page down 34 PageDown PageDown
end 35 End End
home 36 Home Home
left arrow 37 ArrowLeft ArrowLeft
up arrow 38 ArrowUp ArrowUp
right arrow 39 ArrowRight ArrowRight
down arrow 40 ArrowDown ArrowDown
print screen 44 PrintScreen PrintScreen
insert 45 Insert Insert
delete 46 Delete Delete
0 48 0 Digit0
1 49 1 Digit1
2 50 2 Digit2
3 51 3 Digit3
4 52 4 Digit4
5 53 5 Digit5
6 54 6 Digit6
7 55 7 Digit7
8 56 8 Digit8
9 57 9 Digit9
a 65 a KeyA
b 66 b KeyB
c 67 c KeyC
d 68 d KeyD
e 69 e KeyE
f 70 f KeyF
g 71 g KeyG
h 72 h KeyH
i 73 i KeyI
j 74 j KeyJ
k 75 k KeyK
l 76 l KeyL
m 77 m KeyM
n 78 n KeyN
o 79 o KeyO
p 80 p KeyP
q 81 q KeyQ
r 82 r KeyR
s 83 s KeyS
t 84 t KeyT
u 85 u KeyU
v 86 v KeyV
w 87 w KeyW
x 88 x KeyX
y 89 y KeyY
z 90 z KeyZ
left window key 91 Meta MetaLeft event.metaKey is true
right window key 92 Meta MetaRight event.metaKey is true
select key (Context Menu) 93 ContextMenu ContextMenu
numpad 0 96 0 Numpad0
numpad 1 97 1 Numpad1
numpad 2 98 2 Numpad2
numpad 3 99 3 Numpad3
numpad 4 100 4 Numpad4
numpad 5 101 5 Numpad5
numpad 6 102 6 Numpad6
numpad 7 103 7 Numpad7
numpad 8 104 8 Numpad8
numpad 9 105 9 Numpad9
multiply 106 * NumpadMultiply
add 107 + NumpadAdd
subtract 109 NumpadSubtract
decimal point 110 . NumpadDecimal
divide 111 / NumpadDivide
f1 112 F1 F1
f2 113 F2 F2
f3 114 F3 F3
f4 115 F4 F4
f5 116 F5 F5
f6 117 F6 F6
f7 118 F7 F7
f8 119 F8 F8
f9 120 F9 F9
f10 121 F10 F10
f11 122 F11 F11
f12 123 F12 F12
num lock 144 NumLock NumLock
scroll lock 145 ScrollLock ScrollLock
audio volume mute 173 AudioVolumeMute ⚠️ The event.which value is 181 in Firefox. Also FF provides the code value as, VolumeMute
audio volume down 174 AudioVolumeDown ⚠️ The event.which value is 182 in Firefox. Also FF provides the code value as, VolumeDown
audio volume up 175 AudioVolumeUp ⚠️ The event.which value is 183 in Firefox. Also FF provides the code value as, VolumeUp
media player 181 LaunchMediaPlayer ⚠️ The ️ event.which value is 0(no value) in Firefox. Also FF provides the code value as, MediaSelect
launch application 1 182 LaunchApplication1 ⚠️ The ️ event.which value is 0(no value) in Firefox. Also FF provides the code value as, LaunchApp1
launch application 2 183 LaunchApplication2 ⚠️ The ️ event.which value is 0(no value) in Firefox. Also FF provides the code value as, LaunchApp2
semi-colon 186 ; Semicolon ⚠️ The event.which value is 59 in Firefox
equal sign 187 = Equal ⚠️ The event.which value is 61 in Firefox
comma 188 , Comma
dash 189 Minus ⚠️ The event.which value is 173 in Firefox
period 190 . Period
forward slash 191 / Slash
Backquote/Grave accent 192 ` Backquote
open bracket 219 [ BracketLeft
back slash 220 \ Backslash
close bracket 221 ] BracketRight
single quote 222 Quote

The spread of computers and the Internet will put jobs in two categories. People who tell computers what to do, and people who are told by computers what to do.

Marc Andreessen

Источник

Читайте также:  Изменение цвета ссылок на странице

How to test what key on a keyboard is being pressed

Windows Key

Computer Hope

When troubleshooting keyboard problems, you may need to determine if, when keys on the keyboard are being pressed, the computer is recognizing those keys. Below are some web pages and programs that help test the keys on a computer keyboard.

If no keys on your keyboard are working, see: Why don’t any keys on my keyboard work?

JavaScript key event test script

The JavaScript key event test script is a script that tests keypress events. This test can include all keyup and keydown events, and can also include modifier keys.

Windows on-screen keyboard

The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed. Unfortunately, this program does not highlight any of the letter keys as they are pressed.

Passmark KeyboardTest

The Passkmark KeyboardTest is a Windows program that tests the keys pressed on the keyboard with different keyboard layouts.

  • Some keys on my computer keyboard aren’t working.
  • See our key definition for additional information on domain names and related links.
  • Keyboard help and support.

Источник

Swing, слушаем нажатия клавиш

Swing KeyListener, слушаем нажатия клавиш

Для прослушивания нажатий клавиш, существует специальный интерфейс KeyListener:

Каждый метод, реализованный интерфейсом KeyListener, вызывается определенным событием, вместе с которым передается экземпляр KeyEvent. KeyEvent содержит в себе всю информацию о нажатой клавише и о модификаторах, таких как Alt, Ctrl, Shift:

int keyCode = event.getKeyCode(); //цифровой код нажатой клавиши boolean isAltDown = event.isAltDown(); boolean isControlDown = event.isControlDown(); boolean isShiftDown = event.isShiftDown();

Дополнительно про KeyEvent можно почитать тут.

У каждой клавиши есть свой цифровой код, например, код пробела 32, клавиша вправо имеет код 39. Всегда можно посмотреть эти коды, выполнив команду:

System.out.println(event.getKeyCode());

Кроме того, класс KeyEvent содержит коды всех клавиш в статических переменных, все они начинаются на VK_

KeyEvent.VK_SPACE; //32 KeyEvent.VK_RIGHT; //39

Можно и нужно использовать эти переменные для сравнения:

If (event.getKeyCode()==KeyEvent.VK_SPACE)

Короткие нажатия

Когда дело касается только обработки нажатой клавиши, достаточно поместить необходимый код в метод keyTyped() интерфейса KeyListener.

@Override public void keyTyped(KeyEvent event) < //клавиша нажата и отпущена >

Длинные одновременные нажатия

Другое дело, когда нам необходимо обрабатывать не только нажатие, но еще и его длительность и скорее всего сразу у нескольких клавиш одновременно. В этом случае приходится вводить дополнительные переменные, на каждую отслеживаемую клавишу:

private boolean isLeft = false; private boolean isRight = false; private boolean isUp = false; private boolean isDown = false;

Такой подход позволяет реализовывать составные действия, например, длительное движение вправо-вверх одновременно. Необходимо правильно отлавливать события с клавиатуры. Когда зажата клавиша, мы получаем событие в метод keyPressed и записываем эту информацию в переменную. С этого момента мы считаем, что клавиша непрерывно нажата. Если клавиша будет отпущена, мы получим событие в метод keyReleased и обновим об этом информацию в переменной.

@Override public void keyPressed(KeyEvent event) < if (e.getKeyCode()==KeyEvent.VK_LEFT) isLeft = true; if (e.getKeyCode()==KeyEvent.VK_RIGHT) isRight = true; if (e.getKeyCode()==KeyEvent.VK_UP) isUp = true; if (e.getKeyCode()==KeyEvent.VK_DOWN) isDown = true; >@Override public void keyReleased(KeyEvent event)

Некий движок, управляющий нашей программой и живущий в отдельном потоке не слушает нажатия клавиш напрямую. Вместо этого, он работает с переменными, которые мы любезно для него подготовили.

Подключаем слушатель

Остается только повесить наш класс слушателя нажатий на какой-нибудь компонент Swing, например на JFrame:

frame.addKeyListener(keyListener);

Живой пример

Перед вами код, реализующий отрисовку змейки. Голова управляется «стрелками».

Змейка на Java Swing в 100 строк кода

Змейка на Java Swing в 100 строк кода

Листинг RunKeybord.java:

package ru.jcup.education.graphics.swing; import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.JFrame; public class RunKeyboard extends JFrame implements KeyListener < private Thread thread; private static Random random = new Random(); private static final int DIR_STEP = 2; private boolean isLeft = false; private boolean isRight = false; private boolean isUp = false; private boolean isDown = false; private int x, y; public RunKeyboard(int width, int height) < this.setSize(width, height); x = width/2; y = height/2; this.addKeyListener(this); thread = new MoveThread(this); thread.start(); >//Start point public static void main(String. string) < JFrame frame = new RunKeyboard(500,500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); >//Listener @Override public void keyPressed(KeyEvent e) < if (e.getKeyCode()==KeyEvent.VK_LEFT) isLeft = true; if (e.getKeyCode()==KeyEvent.VK_RIGHT) isRight = true; if (e.getKeyCode()==KeyEvent.VK_UP) isUp = true; if (e.getKeyCode()==KeyEvent.VK_DOWN) isDown = true; >@Override public void keyReleased(KeyEvent e) < if (e.getKeyCode()==KeyEvent.VK_LEFT) isLeft = false; if (e.getKeyCode()==KeyEvent.VK_RIGHT) isRight = false; if (e.getKeyCode()==KeyEvent.VK_UP) isUp = false; if (e.getKeyCode()==KeyEvent.VK_DOWN) isDown = false; >@Override public void keyTyped(KeyEvent arg0) <> //Graphics @Override public void paint(Graphics gr) < Graphics2D g2d = (Graphics2D)gr; int r = random.nextInt(256); int g = random.nextInt(256); int b = random.nextInt(256); g2d.setColor(new Color(r,g,b)); g2d.setStroke(new BasicStroke(4f)); g2d.drawOval(x-25, y-25, 50, 50); >public void animate() < if (isLeft) x-=DIR_STEP; if (isRight) x+=DIR_STEP; if (isUp) y-=DIR_STEP; if (isDown) y+=DIR_STEP; this.repaint(); >//Engine thread private class MoveThread extends Thread < RunKeyboard runKeyboard; public MoveThread(RunKeyboard runKeyboard) < super("MoveThread"); this.runKeyboard = runKeyboard; >public void run() < while(true) < runKeyboard.animate(); try < Thread.sleep(10); >catch (InterruptedException e) < e.printStackTrace(); >> > > >

Тут могли располагаться шибко умные слова, великие мысли учёных или изречения скромных блоггеров «jcup.ru». Душераздирающий текст, что заставит прослезиться палача с каменным сердцем. Текст, прочтённый всего лишь раз, способный изменить читателя навсегда. Но, на самом деле, нам нужно было чем-то занять блок внизу.

Источник

Оцените статью