How to listen key pressed event?

Started by Daslee, February 07, 2013, 22:34:38

Previous topic - Next topic

Daslee

Hello, I'm trying to make game not using any game engines, but have problem in keyboard input. This is hardest part for me, to make keyboard listen for key press event, not key down. Here is my current Keyboard.java code:

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Keyboard implements KeyListener {
	private static boolean keys[] = new boolean[65535];

	public void keyPressed(KeyEvent e){
		keys[e.getKeyCode()] = true;
	}

	public void keyReleased(KeyEvent e){
		keys[e.getKeyCode()] = false;
	}

	public void keyTyped(KeyEvent e){
		
	}
	
	public static boolean isKeyDown(int keyCode){
		return keys[keyCode];
	}
}


When I create jframe I do this:
//At the top of class
public Keyboard keyboard = new Keyboard();

//On init jframe:
addKeyListener(keyboard);


And how I could listen for key press in other classes? For example how it would be with LWJGL:
while(Keyboard.next()){
	if(Keyboard.getEventKeyState()){
		//blabla...
	}
}


But I actually do not know what does next() method and getEventKeyState() method. Maybe someone were working with keyboard input and knows how to create those two methods?

quew8


Daslee

That didn't helped me, but I anyway made it. :)
Thanks for help anyway.

Kajos


Daslee

Sure
import java.awt.event.*;

public class Keyboard implements KeyListener {
	private static boolean keys[] = new boolean[65535];
	private static int lastCheckPressed = -1;
	private static int lastPressed = -1;
	
	public void keyPressed(KeyEvent e){
		keys[e.getKeyCode()] = true;
		if(lastCheckPressed != e.getKeyCode()){
			lastPressed = e.getKeyCode();
			lastCheckPressed = e.getKeyCode();
		}
	}

	public void keyReleased(KeyEvent e){
		keys[e.getKeyCode()] = false;
		lastCheckPressed = -1;
	}

	public void keyTyped(KeyEvent e){
	}
	
	public static int getLastPressed(){
		int last = lastPressed;
		lastPressed = -1;
		return last;
	}
	
	public static boolean isKeyDown(int keyCode){
		return keys[keyCode];
	}
}


Usage:
switch(Keyboard.getLastPressed()){
		case KeyEvent.VK_ENTER:
			System.out.println("Haha");
			break;
		}


Keyboard class add as key listener in jframe class or whatever, like this:
addKeyListener(new Keyboard());