Java is not picking up keypresses? - java

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.

Related

The compiler is not recognizing my input for .getPoint

We areto create a plane and have its speed increase 5mph every time the user inputs the up arrow key and decrease 9mph when hitting the down key. It is supposed it report this back to the user in output box whenever whichever action is completed. How do I set it up so that the keylistener will tell the user that they have pressed the up key? Im still working on this so sorry if it is messy.
private class PolygonPanel implements MouseListener, MouseMotionListener, KeyListener
{
public void mousePressed(MouseEvent event){} //unused event
public void mouseDragged(MouseEvent event){} //unused event
public void keyReleased(KeyEvent event){}
public void keyTyped(KeyEvent event){}
//public void keyPressed(KeyEvent event){}
public void keyPressed(KeyEvent event) {
Integer planespeed=event.getKeyCode();
if (event.getKeyCode() == KeyEvent.VK_RIGHT)
{
//Not gonna use this.
}
if (event.getKeyCode() == 39)//KeyEvent.VK_LEFT
{
System.out.print("This key is up");
}
if (event.getKeyCode() == KeyEvent.VK_UP)
{
System.out.print("This key has been pressed");
//speed=planespeed+5;
}
if (event.getKeyCode() == KeyEvent.VK_DOWN)
{
//speed=planespeed-9;
}
repaint();
}
A frame doesn't detect keybaord input if it is not focused on. Therefore, in order to retrieve keyboard input of any kind, you would have to set your frame to be focusable, using a line such as setFocusable(true); in your constructor. You might also have to add a line such as addKeyListener(new PolygonPanel()); so the listener is registered at all.

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.

Java Swing get input

How can I change this code to accept any key (not only F5) and print the key?
component.getRootPane().getInputMap(JRootPane.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "F5 Pressed");
component.getRootPane().getActionMap().put("F5 Pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// Code here
}
});
how can I ("cahnhe") this code to accept any key (not only F5) and print
the key?
sorry this question doesn't make me some sence, in this form
basic is described in tutorial,
component.getRootPane() could be valid only for JFrame, JDialog, JWindow, practically only JFrame has accesible RootPane
otherwise to add Input/ActionMap to the desired JComponent directly
Use KeyboardFocusManager to register a KeyEventDispatcher:
KeboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent ke) {
if (yourComponent.hasFocus && ke.getID == KeyEvent.KEY_TYPED) {
// Your code here
// Use ke.getKeyChar() to detect which key was pressed.
}
}
}

Java AWT KeyListener not working

I have been playing around with Java and I added a KeyListener. When I type a key it prints "0" and I would like it to print the key code.
Key.java
import java.awt.event.*;
public class Key implements KeyListener {
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
System.out.println("TYPED: " + Integer.toString(e.getKeyCode()));
}
}
Main.java
public void init() {
addKeyListener(new Key());
addMouseListener(new Mouse());
this.setBackground(new Color(100, 100, 255));
this.setSize(screen);
}
Thanks for all the help!
Just read the doc :
void keyTyped(KeyEvent e)
Invoked when a key has been typed. See the class description for
KeyEvent for a definition of a key typed event.
So go through the description :
public int getKeyCode()
Returns the integer keyCode associated with the key in this event.
Returns: the integer code for an actual key on the keyboard. (For
KEY_TYPED events, the keyCode is VK_UNDEFINED.)
And the constant VK_UNDEFINED is :
public static final int VK_UNDEFINED = 0;
So that's totally normal you only get 0.
You should use :
public void keyTyped(KeyEvent e) {
System.out.println("TYPED: " + e.getKeyChar());
}
Here's an example using the three methods.
For KEY_TYPED event, the Key Code is undefined. Check the java docs:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode()
Use getKeyChar() instead.

What is the use of keyboard polling?

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.

Categories