keylisteners应该上下移动块,但是当按下或按住键(w,s)时它们什么都不做。 这是代码(我省略了与问题无关的其他类)
感谢您的时间
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))
{
}
}
}
}
答案 0 :(得分:5)
JFrame(all Top-Level Containers)默认情况下永远不会对KeyEvent from KeyListener作出反应,因此无法将KeyListener
添加到JFrame
,使用KeyBindings代替
您可以将KeyListener添加到JPanel (JPanel.setFocusable(true)),但在这种情况下也使用KeyBindings
KeyListener
同时为Keys Shortcuts
提供了三个或更多KeyPressed
的正确聆听