当我按下箭头键时,我试图制作一个在屏幕上移动矩形的程序。目前,在KeyListeners被证明不可靠且相当无用之后,我正在处理键绑定。在尝试使矩形移动之前,我只是试图按下向上箭头键触发System.out.println("Up key pressed!")
,只是为了确保我的KeyBinding实际上正在工作。问题是,他们不是。我正在关注this教程,这与我尝试实现的内容略有不同,但仍应教会我如何使用键绑定。为什么KeyBinding不起作用?
代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GamePanel extends JPanel implements Runnable{
boolean isRunning = true;
int count = 0;
Thread t;
static int rectX = 250;
static int rectY = 250;
Action upAction;
Action downAction;
Action leftAction;
Action rightAction;
public GamePanel()
{
upAction = new UpAction();
t = new Thread(this);
t.run();
/*downAction = new DownAction();
leftAction = new LeftAction();
rightAction = new RightAction();*/
this.getInputMap().put(KeyStroke.getKeyStroke("UP"), "upMotion");
this.getActionMap().put("upMotion",upAction);
}
public void run()
{
loop();
}
public void loop()
{
if(isRunning)
{
Thread t = Thread.currentThread();
try
{
t.sleep(5);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
repaint();
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
count += 1;
g.drawString(Integer.toString(count), 10, 10);
g.drawRect(rectX, rectY, 50, 50);
loop();
}
static class UpAction extends AbstractAction
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Up key pressed!");
rectY++;
}
}
}
主要JFrame代码:
import javax.swing.*;
public class MainFrame{
JFrame frame = new JFrame("Space Invaders");
GamePanel gamepanel = new GamePanel();
public MainFrame()
{
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.add(gamepanel);
}
public static void main(String[] args)
{
new MainFrame();
}
}
答案 0 :(得分:1)
整个问题是你的小组没有焦点,因此无法接收任何输入事件。按照this回答后,添加2行解决了问题:
public GamePanel() {
...
setFocusable(true); //add this anywhere in this constructor
}
public MainFrame() {
...
frame.add(gamepanel);
gamepanel.requestFocusInWindow();
//add this after adding the panel to your frame and making it visible
}
修改强>
此外,您的代码有几个错误:
y--
,因为左上角的坐标为[0,0],x
的轴向右移动,y
向向下< / strong>(与数学课不同)Thread.sleep()
方法中调用paint()
,因为该方法必须尽可能快。thread.run()
的新线程,改为使用thread.start()
,它将实际启动一个新线程,而不是仅调用当前线程中的run
方法。if
方法中将while
更改为loop
,同时从loop
方法移除paint
来解决之前的两个错误。这些不是批评你(每个人都在某个时候开始)而是为了帮助你。