Is there a way to detect two keys at the same time?

Is there a way to detect the keys if the user is holding two keys down at the same time?
[95 byte] By [Miraclesa] at [2007-10-2 9:34:51]
# 1

yes, but you'll have to check outside of the event loop (i.e. don't check for it in the keyPressed method).

just use an array of keys that keeps track of which keys are currently down and which are up. you could use a boolean array but I use an int array because... Im not sure I've just done it probably because of my C background. anyway, basic setup:

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.util.*;

public class MultiKey extends JFrame {

int keys[];

public MultiKey() {

super();

keys = new int[256];

Arrays.fill(keys,0); // 0 = key is up

enableEvents(AWTEvent.KEY_EVENT_MASK);

show();

}

public void processKeyEvent(KeyEvent e) {

// the 0xff below binds the key code to below 256

int key = (e.getKeyCode()&0xff);

if (e.getID() == KeyEvent.KEY_PRESSED) {

keys[key] = 1; // 1 = key is down

}

else if (e.getID() == KeyEvent.KEY_RELEASED) {

keys[key] = 0; // 0 = key is up

}

}

protected boolean isKeyDown(int key) {

return (keys[key] != 0);

}

protected boolean isKeyUp(int key) {

return (keys[key] == 0);

}

}

so now at any time in your code you can check key state by using the isKeyUp and isKeyDown methods. this is about as close as you get to [url=http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4083501]input polling[/url] in java unless you use [url=http://lwjgl.org]LWJGL[/url] or something similiar ;)

you can try out a full executable example at my site [url=http://woogley.net/misc/MultiKey/]here[/url] - just open up the jar and start holding keys down :)

Woogleya at 2007-7-16 23:41:07 > top of Java-index,Other Topics,Java Game Development...