我建立了一个简单的动画程序,可以根据
在JFrame
中使用KeyListener
和ActionListener
按下箭头键(类似于蛇)。但是我注意到,如果我启动该应用程序并移动鼠标,该应用程序将不会继续检查按下了哪个箭头键以及向哪个方向移动。
有人可以向我解释一下吗,是因为我需要禁用某些涉及鼠标事件的操作吗?
这是代码:
public class gui extends JPanel implements ActionListener, KeyListener{
Timer tm = new Timer(5, this);
int x = 300, y = 178, velx = 0, vely = 0;
public gui() {
tm.start();
addKeyListener(this);
setFocusable(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(x, y, 50, 30);
}
@Override
public void keyPressed(KeyEvent e) {
keys(e);
}
public void keys(KeyEvent e) {
int c = e.getKeyCode();
if (c == KeyEvent.VK_LEFT)
{
velx = -1;
vely = 0;
}
if (c == KeyEvent.VK_UP)
{
velx = 0;
vely = -1;
}
if (c == KeyEvent.VK_RIGHT)
{
velx = 1;
vely = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velx = 0;
vely = 1;
}
}
public void borders(ActionEvent e) {
if (x < 0) {
velx = 0;
x = 0;
JOptionPane
.showMessageDialog(null, "you hit the borders you lost!");
System.exit(0);
}
if (x > 530) {
velx = 0;
x = 530;
JOptionPane
.showMessageDialog(null, "you hit the borders you lost!");
System.exit(0);
}
if (y < 0) {
velx = 0;
y = 0;
JOptionPane
.showMessageDialog(null, "you hit the borders you lost!");
System.exit(0);
}
if (y > 330) {
velx = 0;
y = 330;
JOptionPane
.showMessageDialog(null, "you hit the borders you lost!");
System.exit(0);
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent e) {
x += velx;
y += vely;
repaint();
borders(e);
}
}
最佳答案
我不知道你的问题是什么。我使用了您的代码,没有问题。
这是我使用的:
public gui()
{
addKeyListener(this);
setFocusable(true);
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode();
if (c == KeyEvent.VK_LEFT)
{
velx = -1;
vely = 0;
}
if (c == KeyEvent.VK_UP)
{
velx = 0;
vely = -1;
}
if (c == KeyEvent.VK_RIGHT)
{
velx = 1;
vely = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velx = 0;
vely = 1;
}
}
public void actionPerformed(ActionEvent e)
{
x += velx;
y += vely;
repaint();
borders(e);
}
public static void main(String[] args)
{
JFrame frame = new JFrame("gui");
frame.add(new gui());
frame.setVisible(true);
frame.setSize(600, 400);
}
}
在启动程序之前,我单击了鼠标并移动了它,然后使用了按键。它工作正常。虽然我会切换到KeyBindings。