【发布时间】:2015-06-01 01:17:29
【问题描述】:
我扩展了一个 JFrame 类,并将我自己的模型和 JPanel 扩展类作为实例变量。我在我的 JFrame 中实现了 KeyListener,它与箭头键一起工作,但是当我按住键时,我的模型在框架周围移动得非常慢。我的问题是如何将 KeyListener 方法附加到计时器或做一些事情来使我的模型在我按住键时移动得更快。另外,如果可能的话,模型如何同时移动两个方向,比如向左和向上?
public class GameController extends JFrame implements KeyListener,ActionListener
{
private GamePieces p;
private GamePanel panel;
private Timer timer;
public GameController()
{
super("Balls");
setSize(800, 600);
timer = new Timer(10, this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new BorderLayout());
p = new GamePieces();
panel = new GamePanel();
p.addObserver(panel);
c.add(panel);
addKeyListener(this);
panel.update(p, null);
setResizable(false);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (e.getSource() == timer)
{
p.checkEat();
p.moveOthers();
panel.update(p, null);
}
}
public void keyTyped(KeyEvent e)
{
int s = 0;
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key==38)
{
p.up();
panel.update(p, null);
}
else if (key==40)
{
p.down();
panel.update(p, null);
}
else if (key==39)
{
p.right();
panel.update(p, null);
}
else if (key==37)
{
p.left();
panel.update(p, null);
}
}
public void keyReleased(KeyEvent e)
{
int o = 0;
}
public static void main(String[]args)
{
GameController a = new GameController();
a.setVisible(true);
}
}
【问题讨论】:
-
不要使用幻数。你从哪里猜到 37、38、39 和 40 是什么意思?不要使用 KeyListener。相反,您可以使用
Key Bindings。how can the model move two directions at onceMotion Using the Keyboard 中的KeyboardAnimation.java示例展示了如何使用键绑定来做到这一点。
标签: java timer keylistener