Reputation: 133
The keylisteners are supposed to move the block up and down but when the keys (w, s) are pressed or held they do nothing. Here is the code (I'm omitting the other class which has nothing to do with the problem)
Thank you for your time
import java.awt.event.KeyEvent;
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame
{
private static final long serialVersionUID = 1L;
JFrame f = new JFrame();
public void Draw()
{
Handler handle = new Handler();
f.addKeyListener(handle);
f.setFocusable(true);
f.requestFocusInWindow();
}
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setSize(400, 250);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class Handler extends JFrame implements KeyListener
{
private static final long serialVersionUID = 1L;
public void keyTyped(KeyEvent e)
{
}
@Override
public void keyPressed(KeyEvent e)
{
if ((e.getKeyCode() == KeyEvent.VK_S))
{
System.out.println("testw");
}
if ((e.getKeyCode() == KeyEvent.VK_W))
{
}
}
@Override
public void keyReleased(KeyEvent e)
{
if ((e.getKeyCode() == KeyEvent.VK_UP))
{
}
if ((e.getKeyCode() == KeyEvent.VK_DOWN))
{
}
}
}
}
Upvotes: 0
Views: 141
Reputation: 109823
JFrame (all Top-Level Containers) by default never to react to KeyEvent from KeyListener, then isn't possible to add KeyListener
to JFrame
, use KeyBindings instead
you can to add KeyListener to JPanel (JPanel.setFocusable(true)), but use KeyBindings
in this case too
KeyListener
is correct listener for Keys Shortcuts
for three or more KeyPressed
in the same time
Upvotes: 5