What is the use of keyboard polling? - java

I am making a 2d graphics application using Java 1.6 .For receiving keyboard inputs ,i just use the addKeyListener() on the JPanel and in one of the callback methods keyPressed (KeyEvent ke) ,i do the drawing stuff
`public void keyPressed(KeyEvent ke)
{
keyName=KeyEvent.getKeyText(ke.getKeyCode());
/*calling other classes ,calculating values
and drawing on the jpanel (moving an image ,etc)
*/
ke.consume();
}`
But there is another approach that i found in some blogs which goes something like this ,
1.)First initialize a boolean[] keys=new boolean[256];
2.)then, for each key event received ,just store the value into this boolean array.
`public void keyPressed(KeyEvent ke)
{
//storing the keyevent:true since its due to key being pressed
keyMap[ke.getKeyCode()]=true;
ke.consume();
}`
`public void keyReleased(KeyEvent ke)
{
//storing the keyevent:false since its due to key being released
keyMap[ke.getKeyCode()]=false;
ke.consume();
}`
finally there is method which loops through the boolean[] and checks the key state..
`for(int i=0;i<keyMap.length;i++)
{
if(keyMap[i]==true)
{
/* do some graphic tasks...*/
}
}`
whats the difference between the two patterns?

The 2nd approach allows you to have more than one keys pressed at the same time, usually to allow diagonal movement with double key presses.

Related

KeyEvents are not received when pressing keys at the same time

I'm programming a game in java that has two players on the same keyboard. If one of the players is holding their forward button and the second player presses his forward button the first player is stopped. This happens the other way around too and I'm not sure how to fix it.
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
paddle.keyPressed(e);
paddletwo.keyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
paddle.keyReleased(e);
paddletwo.keyReleased(e);
}
In each paddle class I also have this:
public void keyReleased (KeyEvent e) {
ya = 0;
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP)
ya = -pong.speed;
if(e.getKeyCode() == KeyEvent.VK_DOWN)
ya = pong.speed;
}
Player two uses VK_W and VK_S instead of UP and DOWN.
This is related to the actual hardware keyboard. To reduce costs the control lines are shared so that it's impossible to push a certain combination of keys at the same time.
Either buy a high-end keyboard or choose the keys carefully so there is minimal interference (of course this is harder the more keys you use, and it will result in some funny looking controls).
Here's the reason explained.
Edit:
Actually this shouldn't affect when only 2 keys are involved, only with 3 or more.

Methods with event handling giving me errors

Sorry for bad title but didn't know what else to say.
So I am trying to add a little piece of code into a game I am making so that you can make the player jump by pressing any key or using the mouse. I pretty much copied the code that makes the player jump by pressing the mouse into the code that makes him jump by keyboard keys ( risky but I like to live on the edge) but it gives me the error:
The method KeyPressed(KeyEvent) from the type new KeyAdapter(){} is never used locally
from this:
this.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent arg0) {
player.jump();
}
});
this.addKeyListener(new KeyAdapter(){
public void KeyPressed(KeyEvent arg0) {
player.jump();
}
});
}
I have searched the whole game but found no other things that have the word 'mouse' in them and I am also new to this. I'm sure i'm missing something obvious.

Listener mouse entered and key pressed at the same time

I have JFrame which contains JPanel. How to write listener to check when key(let it be SHIFT) is pressed and mouse enters to the JPanel area at the same time?
The MouseEvent provides information about the state of various elements, including some keys, via it's modifier properties, for example...
#Override
public void mouseEntered(MouseEvent e) {
int modifiersEx = e.getModifiersEx();
int onmask = MouseEvent.SHIFT_DOWN_MASK;
if ((modifiersEx & onmask) == onmask) {
// Shift key is down
}
}
Will allow you to detect when the Shift key is pressed when the mouse enters a given component.
Take a look at...
MouseEvent
How to Write a Mouse Listener
...for more details

JtextArea cursor position after keypress of ENTER

Guys weird problem im facing
Basically i have 2 textAreas... (diplaybox and textbox)
while typing in textbox, the moment "Enter" is pressed i want all the text entered in textbox to go to displaybox... and textbox should be empty...
it all works fine, except...
after the text is transfered the cursor position of the textbox isnt on the topmost left side... it is somehow blinking on one line below that!(possibly because "ENTER" still got excecuted)... please see code
any ideas?
thanks in advance... just need the cursor to go back to the topmost left like how it is when we start typing ... without having to use KeyReleased event... something isnt feeling right... im sure this isnt he way it is actually done.. what say?
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)// | (e.getKeyCode() == KeyEvent.VK_B))
{ //Toolkit.getDefaultToolkit().beep();
displaybox.append(textbox.getText() + "\n");
//textbox.setCaretPosition(0);
//textbox.setText("");
System.out.println(textbox.getCaretPosition());
}
}
public void keyTyped(KeyEvent e)
{}
public void keyReleased(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{textbox.setCaretPosition(0);
textbox.setText("");
System.out.println(textbox.getCaretPosition());
}
}
All Swing components work by using Key Bindings. The default binding for the Enter key is to add a newline string to the text area. If you want to change the functionality of the Enter key then change the default Action. Don't attempt to use a KeyListener.
Check out Key Bindings for a program to list all the default bindings as well as a link to the Swinng tutorial on How to Use Key Bindings. If you run the program you will find that the Enter key invokes an Action identified by the "insert-break" tag in the ActionMap. So to replace the Action you can do something like:
Action enter = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
displayBox.append( textBox.getText() + "\n" );
textBox.setText("");
}
};
textBox.getActionMap().put("insert-break", enter);
The problem with using the KeyListener is that the default Action is still invoked AFTER you process the KeyEvent.

Java is not picking up keypresses?

I have a program which produces a JFrame and then a JPanel on top of it. For the program, I have tried implementing the KeyListener and then adding the methods (for both components), but the program does not pick any of my key strokes up. What am I doing wrong?
EDIT
This is my code. It is a part of the class which creates the JFrame. It still does not pick up the press of the ESC key.
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_ESCAPE){
System.out.println("Hi");
}else{
System.out.println("Hello");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
Without your code, all I can tell you is that usually when people ask this they don't know that the interface KeyListener contain three methods as Agusti-N states in their answer here:
void keyTyped(KeyEvent)
void keyPressed(KeyEvent)
void keyReleased(KeyEvent)
If you use keyTyped and you are using event.getKeyCode() to check for the character entered, this will not work. You should use getKeyChar() for keyTyped and getKeyCode() for keyPressed and keyReleased. Otherwise you'll get null.
You should only use this if you do not have any other alternative, in most cases you want to use Key Bindings.

Categories