Detecting multiple key presses
Using the code below I am trying to detect keypresses for a java applet which involves holding down of several keys at once. I have 2 problems, probably related. Firstly I can only detect 3-4 simultaneous keys being held down and secondly the keyPressed and released! events are continually fired while a key is held down not just when it was first pressed as you would think. I would like to be able to detect up to a maximum of 16 keys being held down at once, is this possible? I am working on a unix system in x-windows which I think accounts for the auto-repeat problem, but why am I having trouble detecting multiple simultaneous keys being held down?
It there a boolean function I can call to check the state of given keys at a given time, that would be very useful?
Any help is appreciated.
Ian
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch(keyCode){
case java.awt.event.KeyEvent.VK_O: //o
odown=true;
break;
case java.awt.event.KeyEvent.VK_P: //p
pdown=true;
break;
case java.awt.event.KeyEvent.VK_Q: //q
qdown=true;
break;
case java.awt.event.KeyEvent.VK_W: //w
up=true;
break;
case java.awt.event.KeyEvent.VK_A: //a
left=true;
break;
case java.awt.event.KeyEvent.VK_S: //s
down=true;
break;
case java.awt.event.KeyEvent.VK_D: //d
right=true;
break;
}//method keypressed
public void keyTyped(KeyEvent e) {
}//method keytyped
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
switch(keyCode){
case java.awt.event.KeyEvent.VK_O: //o
odown=false;
break;
case java.awt.event.KeyEvent.VK_P: //p
pdown=false;
break;
case java.awt.event.KeyEvent.VK_Q: //q
qdown=false;
break;
case java.awt.event.KeyEvent.VK_W: //w
up=false;
break;
case java.awt.event.KeyEvent.VK_A: //a
left=false;
break;
case java.awt.event.KeyEvent.VK_S: //s
down=false;
break;
case java.awt.event.KeyEvent.VK_D: //d
right=false;
break;
}//method keyReleased
Did you ever find a solution to this problem. I am experiencing a similar problem. I want to be able to disable the auto-repeat function of the keyboard, so that I can tell if the user is holding down the key, or pressing it several times.
If you have found a solution please let me know at [email protected]
Thanks,
Ben Newton
Similar Messages
-
When I hold Tab + w space doesn't work click (I have my controls set as this for a game).
Is there anyway to make it so i can hold those two keys and have spacebar work?
Im on a MacBook Pro Retina 13 inch with latest version of yosemite
Thanks for the helpHere is an example of both multiple key press and repeat delay ignore. It is a terrible example of animation. Do not us this animation loop in a game. It will flicker far too much.import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame implements Runnable {
boolean upPressed=false, downPressed=false, leftPressed=false, rightPressed=false;
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_UP: upPressed = true; break;
case KeyEvent.VK_DOWN: downPressed = true; break;
case KeyEvent.VK_LEFT: leftPressed = true; break;
case KeyEvent.VK_RIGHT: rightPressed = true; break;
public void keyReleased(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_UP: upPressed = false; break;
case KeyEvent.VK_DOWN: downPressed = false; break;
case KeyEvent.VK_LEFT: leftPressed = false; break;
case KeyEvent.VK_RIGHT: rightPressed = false; break;
setSize(250,250);
setVisible(true);
Thread timer = new Thread(this);
timer.start();
public static void main(String[] args) {
new Test();
public void run() {
while (true) {
repaint();
try { Thread.sleep(30);} catch (Exception e) {}
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(0,0,getWidth(), getHeight());
g.setColor(Color.black);
g.drawString("Up",40,40);
if (upPressed) g.drawString("Pressed",100,40);
g.drawString("Down",40,60);
if (downPressed) g.drawString("Pressed",100,60);
g.drawString("Left",40,80);
if (leftPressed) g.drawString("Pressed",100,80);
g.drawString("Right",40,100);
if (rightPressed) g.drawString("Pressed",100,100);
} -
Multiple key press's with Bluetooth Keyboard
I'm ready to update my mac to a new G5 imac and fancy getting the wireless bluetooth keyboard and mouse with it.
I have one question, has anyone experienced problems when holding down multiple keys on the keyboard and moving the mouse all at once (Using illustrator)?
In my office I have the misfortune of having to use a PC, I have had a number of wireless keyboard and mouse combos, all of them when using Illustrator and photoshop can not handle multiple key press's and mouse movement.
ie if I'm duplicating an object by dragging a copy of it across the screen, on the PC it will work but it always "releases" after a couple of seconds and drops the copy in the where I don't want it which gets very frustrating (this only happens with wireless).
As I do a lot of work at home, I hoping this wont be the case with the mac's bluetooth K & M.
thanks
RussellThe shift key works just fine on my Bluetooth keyboard. So I would imagine this is an issue with your keyboard.
-
Hai all
How can a j2me application withstand multiple key press while doing some process.
Please help me with some ideas
Thanks
JineshProblem is, Redtruck, I can only get FCP to register one press of t. I can reasign select all tracks forward to a single t but when i go to select track forward and press t it asks me if i want to reassign t to this command and then overrides the select all forward shortcut (which reverts back to tttt automatically).
I can't seem to find a way to enter multiple "t"s when assigning a shortcut.
I hope this makes sense (I'm almost confusing myself). -
How to detect any key pressed for program running in the background?
Hi All,
is it possible to detect when any key is pressed if a java program is not in the focus? For example, when I have a console based program I can write something like:
System.in.read();
and wait until any key is pressed. However, if I move the mouse away from the console and make any other window active, the console program "doesn't hear" anything. Ok, it's clear, of course, but how is it possible to make the program detect any keys pressed even if it's running in the background?
Thanks a lot for any hints!qnx wrote:
1) Stop trying to make spyware. -> I don't do anything like this!
2) Stop re-posting the same questions. -> didn't know they are the same, sorry.
3) Stop taking us for fools. -> what? Honestly, I don't think that I realy deserved this :)With a limited posting history and the type of questions you are asking they are unusual.
There are very few legitimate problem domains that would require what you are asking about. There are illegitimate ones though. And the legitimate ones would generally require someone with quite a bit of programming experience and would also be required (the fact that java can't do it would not get rid of the requirement.)
Thus one might make assumptions about your intentions. -
To detect a key press, i know i have to use the keylistener class
public class key implements KeyListener{
public static void main (String args[]){
addKeyListener(this);
keyReleased(KeyEvent e) {}
keyTyped(KeyEvent e) {}
keyPressed(KeyEvent e) {
I built a simple program but it doesn't compile, it has an error.
All i want is to detect a key press and do something for key presses...
What am i doing wrong?I once got the following demo file somewhere in the Sun/Java site, probably in one of the link cited above..
* Swing version
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
public class KeyEventDemo extends JApplet
implements KeyListener,
ActionListener {
JTextArea displayArea;
JTextField typingArea;
static final String newline = System.getProperty("line.separator");
public void init() {
JButton button = new JButton("Clear");
button.addActionListener(this);
typingArea = new JTextField(20);
typingArea.addKeyListener(this);
displayArea = new JTextArea();
displayArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(displayArea);
scrollPane.setPreferredSize(new Dimension(375, 125));
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(typingArea, BorderLayout.NORTH);
contentPane.add(scrollPane, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setContentPane(contentPane);
/** Handle the key typed event from the text field. */
public void keyTyped(KeyEvent e) {
displayInfo(e, "KEY TYPED: ");
/** Handle the key pressed event from the text field. */
public void keyPressed(KeyEvent e) {
displayInfo(e, "KEY PRESSED: ");
/** Handle the key released event from the text field. */
public void keyReleased(KeyEvent e) {
displayInfo(e, "KEY RELEASED: ");
/** Handle the button click. */
public void actionPerformed(ActionEvent e) {
//Clear the text components.
displayArea.setText("");
typingArea.setText("");
//Return the focus to the typing area.
typingArea.requestFocus();
* We have to jump through some hoops to avoid
* trying to print non-printing characters
* such as Shift. (Not only do they not print,
* but if you put them in a String, the characters
* afterward won't show up in the text area.)
protected void displayInfo(KeyEvent e, String s){
String charString, keyCodeString, modString, tmpString;
char c = e.getKeyChar();
int keyCode = e.getKeyCode();
int modifiers = e.getModifiers();
if (Character.isISOControl(c)) {
charString = "key character = "
+ "(an unprintable control character)";
} else {
charString = "key character = '"
+ c + "'";
keyCodeString = "key code = " + keyCode
+ " ("
+ KeyEvent.getKeyText(keyCode)
+ ")";
modString = "modifiers = " + modifiers;
tmpString = KeyEvent.getKeyModifiersText(modifiers);
if (tmpString.length() > 0) {
modString += " (" + tmpString + ")";
} else {
modString += " (no modifiers)";
displayArea.append(s + newline
+ " " + charString + newline
+ " " + keyCodeString + newline
+ " " + modString + newline);
} -
Detecting two keys press at one time
i need to do a event handler, say when user press shift + enter, it will do something, else enter would do another thing
i tried but i can't get the event handler to detect two key press, how do I go about it?VK_ENTER vs (VK_ENTER + SHIFT_DOWN_MASK)
-
How do you register multiple key presses at the same time?
Hi. I'm trying to write a first person game in OpenGL and I'm having some trouble with key listening. Right now I just use the basic AWT KeyListener. The problem that arises is that whenever I hold down a key, such as a movement key, there is a short pause after it moves me in the appropriate direction, and only after the pause does it start continuously moving me. In addition to that, I can't press multiple keys at once to get diagonal movement (I use WASD for movement). Is there something I can do with AWT to fix both of these problems, or is there something other than AWT that I should use that would be better?
the pause is the typomatic rate of the keyboard, you can avoid that by using the keyPressed and setting a flag then a sleep(myDelayTime).... if they keyRelease--and clearing of the flag--hasn't happened after the sleep, then you're key is still down so keep firing, moving, or what ever.
-
Detecting a key pressed anywhere
How do you detect a key that is pressed no matter what window is selected?
System.in.read()Because Windows only has Canonical mode for its DOS input,
this always blocks which may not be what you want.
see the example I posted earlier.
http://forum.java.sun.com/thread.jspa?threadID=664543&messageID=3892105#3892105
(T) -
Detecting asyncronous key press
Hi all, I'm trying to figure out whether there is any way to detect an asynchronous key press for a simple and line-oriented java task.
I mean no GUI, AWT and alike.
All examples I could see refer to AWT events.
The goal is to break long and time consuming processes upon pressing (for example) ctrl-c like we used to to in C++.
Thanks.Word is not a JVM mastered process.
I'm referring to what it seems the standard behavior of the JVM. I can be notified about ctrl-c, but I cannot change its standard action of terminating the JVM process.
I tried by catching SIGINT using sun.misc.* - it works fine, handler is called - however upon returning (even without calling the previous handler - if any) the process exits.
I don't see any way to change this - which was my primary goal. -
Using InputMap and ActionMap to detect any key pressed...plz help
Hi,
I am quite new to Java. I have a tiny problem. I wanna put an actionlistener into a JTextField, so it printout something whenever a key is pressed (when the textField is selected).
I can only get it to print if I assign a specific key to pressed...example below (works):
JTextField searchBox = new JTextField();
InputMap imap = searchBox.getInputMap();
ActionMap amap = searchBox.getActionMap();
imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "pressed");
amap.put("pressed", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("TYPEEEEEEEEEEEEEEE");
HOWEVER, when i change keystroke to any key pressed, it doesn't work. Example below(doesn't work):
JTextField searchBox = new JTextField();
InputMap imap = searchBox.getInputMap();
ActionMap amap = searchBox.getActionMap();
imap.put(KeyStroke.getKeyStroke(KeyEvent.KEY_PRESSED, 0), "pressed");
amap.put("pressed", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("TYPEEEEEEEEEEEEEEE");
Somebody plz helps me. I am really confused how to use KeyEvent.KEY_PRESSED. I thought it would work the same way as KeyEvent.VK_A...if i can't use KEY_PRESSED for that purpose, what KeyEvent do I use?
Thank you very much in advance.Sounds like you want a KeyListener.
textField.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
System.out.println("Key typed.");
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed.");
public void keyReleased(KeyEvent e) {
System.out.println("Key released.");
});See the API documentation for more information. -
Recognizing multiple key presses in As3
Hi,
I have a simple game with three keyboard inputs - left, right and fire
I want to be able to log when a key is pressed and released. In the game, you can be in the following states:
None
Left only - keyz on the keyboard
Right only - keyc on the keyboard
Fire only - keyx on the keyboard
Left and Fire - keyz and Keyx on the keyboard
Right and Fire - Keyc and Keyx on the keyboard
When Left key is pressed for example, it should log LeftKeypressStart and when it is released, it shoul log leftKeyPressStop. The same should happen to Right and Fire keys when they are pressed individually.
Now, for the game to be in Left and Fire state either of the three conditions are true:
Left key can be pressed and held down before the fire button is pressed and held down or
Fire button is pressed and held down before left is pressed and held down or
Both keys pressed down simultenuosly (although this condition will rarely occur as we are not robots)
Similar conditions should be true for the game to be in the Right and Fire State
Now considering the first condition,when Left key is down, I want the game to log LeftKeypressStart but as soon as the Fire key is down, it should log LeftKeyPressStop and also Log LeftandFireKeypressStart. Then if Fire is released first, I want it to log LeftandFirKeypressStop and then log LeftKeyStart. but if Left is released first, it should log LeftandFirKeypressStop and then lof FireKeyPressStart.
This is what I have at the minute:
private function onKeyPress (evt:KeyboardEvent)
if (evt.keyCode == 67 && evt.keyCode !=88 && evt.keyCode != 90)
//log Right
else if (evt.keyCode != 67 && evt.keyCode !=88 && evt.keyCode == 90 )
//log Left
else if (evt.keyCode != 67 && evt.keyCode !=90 && evt.keyCode == 88)
//log Fire
else if (evt.keyCode == 67 && evt.keyCode !=90 && evt.keyCode == 88 )
//log RF
private function onKeyRelease(evt:KeyboardEvent)
if (evt.keyCode == 67 && evt.keyCode !=88 && evt.keyCode != 90)
//stop right
else if (evt.keyCode != 67 && evt.keyCode !=88 && evt.keyCode == 90 )
//stop Left
else if (evt.keyCode != 67 && evt.keyCode !=90 && evt.keyCode == 88)
//stop Fire
else if (evt.keyCode == 67 && evt.keyCode == 88 && evt.keyCode !=90 )
// stop RFThere can only be one evt.keyCode per keypress, so your approach will not work. All you need to do is determine which key caused the function to execute. If you want to keep track of which keys are down, just create three Boolean variables, as in...
var leftDown:Boolean = false;
var rightDown:Boolean = false;
var fireDown:Boolean = false;
and set those values to true or false and make use of them in whatever other code you intend.
private function onKeyPress (evt:KeyboardEvent)
if (evt.keyCode == 67)
rightDown = true
else if (evt.keyCode ==88)
leftDown = true
else if (evt.keyCode == 88)
fireDown = true
// process per whatever values are true/false
and in the key up function set them back to false in a similar fashion. -
How to detect space key pressed event
I am working on a japplet where it is needed to pause the applet on the occurrence of a space bar key pressed event can anybody help
thanks in advanceHave a look at the tutorial:
http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
-Puce -
I am using this code to set up a listener for a key press. I
noticed that it works fine when you use a LEFT, RIGHT etc. press,
but it will not work with a regular key press(i.e. ctrl+P). It says
that there is an undefined property as far as the Letter goes. If
anyone can help me with this, I would very much appreciate it.
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
function keyDown(event:KeyboardEvent):void
if(event.ctrlKey)
var key = event.keyCode;
var P_key = Keyboard.P;
switch(key)
case P_key:
trace("this thing works");
break;
}Ok, I've figured it out. Flash decided to take me for a fool
and pretended like it would take the P-key as a press, but in
actuality, it only works that way in AIR. -
Assigning multiple key press in shortcuts keyboard
I find that i use the select all tracks forward far more than select track forward so would like to change my shortcuts to t for select all tracks and tt for select track. Problem is that I can't get Customize Keyboard to accept multiple presses of t - it simply registers the single press of t and asks if I want to change the shortcut it is assigned to.
Any ideas?
Thanks.Problem is, Redtruck, I can only get FCP to register one press of t. I can reasign select all tracks forward to a single t but when i go to select track forward and press t it asks me if i want to reassign t to this command and then overrides the select all forward shortcut (which reverts back to tttt automatically).
I can't seem to find a way to enter multiple "t"s when assigning a shortcut.
I hope this makes sense (I'm almost confusing myself).
Maybe you are looking for
-
A few days ago I updated to firefox 9.0.1, and when I am using firefox in the My Yahoo account, I can see my emails, but when I click on one to open it, I am asked to put in my password for yahoo. This shouldn't occur because it already know who I am
-
The document could not be saved. there was a problem reading this document (109)
Have Vista and get this error msg when trying to save Doc as pdf. Document created online as result of survey and opens fine, just cannot save it to a file folder for future access.
-
I just today bought an xbox 360 and i tried connecting my ipod video to it but for some reason after i select the song to be played absoloutly nothing happens. Please help me resolve this issue. I appriciate the help thank you.
-
New in Oracle forms and I need help
Good afternoon to all of you. I need a help for my problem. I have 7 tables and i create a form with 7 blocks in oracle 10g. The items are lists and text items. I am trying to choose a value from the list or write something into the text items and i
-
Not able to change company code in CNMASS after cost planning/Budgeting
Hi experts, After cost planning in my project, i was trying to change company code through CNMASS, but system is not allowing me to do that. Is there any notes/alternate solution, through which i can change the company code after cost planning or bud