矩形不使用箭头键移动 [英] Rectangle is not moving with arrow keys

查看:23
本文介绍了矩形不使用箭头键移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作简单的游戏,但我的第一个问题是当我按下箭头键时我的矩形没有移动.

I am trying to make simple game but my first problem is that my rectangle is not moving when I press the arrow keys.

这是我的代码:

public class Gameseeting extends JPanel implements ActionListener, KeyListener
{
  Timer tt= new Timer(5, this);
  int x=2, y=210, velx=0,vely=0;
  Gameseeting ()
  {
    tt.start();
    setFocusable(true);
    addKeyListener(this);
    setFocusTraversalKeysEnabled(false);
  }
  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    g.drawRect(x, y, 40, 50);
  }

  public void actionPerformed(ActionEvent ae)
  {

    x += velx;
    y += vely;
    repaint();
  }

  public void keyPressed(KeyEvent e)
  {
    int code = e.getKeyCode();

    if (code == KeyEvent.VK_DOWN) {
      vely = 1;
      velx = 0;
    }
    if (code == KeyEvent.VK_UP) {
      vely = -1;
      velx = 0;
    } 
    if (code == KeyEvent.VK_LEFT) {
      vely = 0;
      velx = -1;
    }
    if (code == KeyEvent.VK_RIGHT) {
      vely = 0;
      velx = 1;
    }
  }

  public void keyTyped(KeyEvent ke)
  {
  }

  public void keyReleased(KeyEvent ke) {
    velx=0;
    vely=0;
  }
}

我需要你的帮助,请告诉我我做错了什么.谢谢!

I need your help and please tell me what I'm doing wrong. Thanks!

推荐答案

我已经阅读了你的代码好几遍了,没有任何地方让我觉得不正确.所以我创建了一个小启动程序,它创建了一个 JFrame,并将您的自定义 JPanel 作为内容窗格...

I've read over your code several times, and nothing jumps out at me as not being correct. So I created a little launch program which creates a JFrame with your custom JPanel as the content pane ...

public class MoveRectangleArrowKeys {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(MoveRectangleArrowKeys::new);
    }

    MoveRectangleArrowKeys() {
        JFrame frame = new JFrame("Move Rectangle with Arrow Keys");
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new Gameseeting());
        frame.setVisible(true);
    }
}

...它按预期工作.

所以,问题出在别处.无论是在面板的创建中,还是在与其他代码的互操作中,或在其预期行为中.

So, the problem lies elsewhere. Either in the creation of the panel, or its interoperation with other code, or with its expected behaviour.

首先,创造.Swing 组件应该只在 Swing 的事件调度线程 (EDT) 上创建.如果您在 main 方法创建应用程序的时候没有使用 SwingUtilities.invokeAndWait(...)SwingUtilities.invokeLater(...)UI,您可能会将 Swing 置于不良状态.

First, creation. Swing components should only ever be created on Swing's Event Dispatching Thread (EDT). If you are not using SwingUtilities.invokeAndWait(...) or SwingUtilities.invokeLater(...) when your main method creates the application's UI, you could be putting Swing into a bad state.

其次,与其他代码的互操作.您已调用 setFocusable(true);,这使您的组件可聚焦.但是如果框架中有多个可聚焦组件,则焦点可能会被另一个 UI 元素占据.尝试在面板中单击鼠标.如果矩形开始响应箭头键,那么您可能只需要调用 requestFocusInWindow() 在您的 Gameseeting 面板上,在框架变得可见后.

Second, interoperation with other code. You've called setFocusable(true);, which makes your component focusable. But if there is more than one focusable component in the frame, the focus may be taken by another UI element. Try a mouse click in your panel. If the rectangle begins responding to the arrow keys, then you may simply need to call requestFocusInWindow() on your Gameseeting panel after the frame has become visible.

第三,您的期望可能是错误的.如果您按数字小键盘上的向上箭头,您可能希望矩形响应 VK_UP 代码而移动,但事实并非如此.该代码需要测试 VK_NUMPAD8 代码.

Third, your expectations may be in error. If you are pressing the UP arrow on the numeric keypad, you may expect the rectangle to move in response to the VK_UP code, but it won't. The code would need to test for the VK_NUMPAD8 code.

无论如何,发布的代码是有效的.如果您已经简化了代码以将其发布到 StackOverflow 上,您可能无意中删除了问题代码.如果您没有对其进行简化,则问题出在您项目中的其他代码上.如果以上提示对您没有帮助,您需要编辑您的帖子以添加更多信息(和代码),以便我们重现问题并提出解决方案.

At any rate, the code as posted works. If you have simplified the code to post it on StackOverflow, you may have inadvertently removed the problem code. If you haven't simplified it, the problem is with other code in your project. If the above tips have not helped you, you will need to edit your post to add more information (and code) in order for us to replicate the problem and come up with a solution.

记得发布一个最小的完全可验证示例.您发布的代码不完整;我必须添加上面的启动器代码来创建和测试您的自定义 JPanel.由于它没有说明问题,因此它不是一个可验证的示例.可能是启动代码有问题,你的启动代码失败了,但我的没有.最小"意味着删除所有不需要重现问题的不必要代码.例如,您可以删除 VK_UPVK_LEFTVK_DOWN 代码,只留下 VK_RIGHT 代码.这是一个最小化,它仍然可以使代码完成".但是删除 JPanel 的构造并没有给您留下完整的示例.测试您发布的代码,并确保它仍能说明问题;否则我们只能猜测真正的问题.

Remember to post a Minimal Complete Verifiable Example. Your posted code was not complete; I had to add the above launcher code to create and test your custom JPanel. Since it does not demonstrate the problem, it is not a verifiable example. It may be that the launch code is problem, and it fails with your launch code, but not with mine. "Minimal" means removing all the unnecessary code that is not required to reproduce the problem. For example, you could remove the VK_UP, VK_LEFT, and VK_DOWN code, leaving just the VK_RIGHT code. That is a minimization, which could still leave the code "Complete". But removing the construction of the JPanel does not leave you with a complete example. Test the code that you post, and make sure that it still demonstrates the problem; otherwise we can only guess at the real problem.

这篇关于矩形不使用箭头键移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆