I want to catch the Clicked event in java when key pressed (not ctrl, or shift, or alt), or check if key "A" press druing key "D" pressed. How can i do that, something like the method isshiftdown ?
How to check if key pressed when clicked event in java
6.3k views Asked by PhoenixRg At
4
There are 4 answers
0
On
What I like to do is have a Boolean array to store the currently pressed keys, and then use other methods to access them when needed. For example...
Boolean[] keys = new Boolean[256];
Boolean mousePressed = false;
...
keyPressed(MouseEvent e) {
keys[e.getKeyCode()] = true;
}
...
keyReleased (MouseEvent e) {
keys[e.getKeyCode()] = false;
}
....
mousePressed (MouseEvent e) { mousePressed=true; }
Then whenever you need to see it a combination of keys was pressed, just reference the array and see if that key is currently true. It works equally well for both mouse and key listeners.
0
On
You can do it by making an array of booleans and when the key is pressed set that key's boolean to true and when not pressed set it to false.
public boolean[] key = new boolean[68836];
Dont ask me why it is 68836... Your class would look something like this:
public class keyHandler implements KeyListener, MouseListener{
int KeyCode = 0;
Main main;
public KeyHandler(Main main){
this.main = main;
}
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
if (keyCode > 0 && keyCode < key.length) {
main.key[keyCode] = true;
}
}
public void keyReleased(KeyEvent e) {
keyCode = e.getKeyCode();
if (keyCode > 0 && keyCode < key.length) {
main.key[keyCode] = false;
}
}
public void mousePressed(MouseEvent e) {
main.MouseButton = e.getButton();
main.MousePressed true;
}
public void mouseReleased(MouseEvent e) {
main.MouseButton = 0;
main.MousePressed = false;
}
}
Next you would have some kind of loop class to allow you to check the booleans regularly:
public class Time extends Thread{
Main main;
public Time(Main main){
this.main = main;
}
public void run(){
while(true){
main.update();// you would probably want some timing system here
}
}
}
Then in your main class or something:
public class Main {
//whatever you have here
public boolean[] key = new boolean[68836];
int MouseButton = 0;
boolean MousePressed = false;
public Main(){
Component c; //whatever you are using e.g JFrame
//whatever you do to your component
KeyHandler kh = new KeyHandler(this);
c.addKeyListener(kh);
c.addMouseListener(kh);
}
public void update(){
if(key[KeyEvent.VK_A] && key[KeyEvent.VK_D){
//both keys are pressed
}
}
}
add a mouse listener like this:
and the key listener: