【发布时间】:2014-09-19 13:12:14
【问题描述】:
我正在尝试制作一个程序,当按下箭头键时,它会在屏幕上移动一个矩形。目前我正在研究键绑定,在 KeyListeners 被证明不可靠且相当无用之后。在尝试移动矩形之前,我只是尝试按下向上箭头键触发System.out.println("Up key pressed!"),只是为了确保我的 KeyBindings 实际工作。问题是,他们不是。我正在关注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();
}
}
【问题讨论】:
-
你的主要在哪里?无法运行此代码。
-
@kai 我的主要代码只是创建了一个 JFrame 并将这个类作为 JPanel 添加到其中
-
那个循环坏。它将暂停调用构造函数的当前线程,因此您无法在任何地方运行 Panel(除非您从构造函数导出
this)。尝试在新线程中运行loop方法。 -
添加你的主代码,这样我就可以运行它了。
-
@kajacx 我已经编辑了我的代码。不,即使在我编辑之前,我仍然看到一个快速增加的数字并且绘制了一个矩形
标签: java swing paintcomponent key-bindings thread-sleep