简体   繁体   English

矩形不使用箭头键移动

[英]Rectangle is not moving with arrow keys

I am trying to make simple game but my first problem is that my rectangle is not moving when I press the arrow keys. 我正在尝试制作简单的游戏,但是我的第一个问题是,当我按箭头键时,矩形没有移动。

This is my code: 这是我的代码:

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! 谢谢!

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 ... 因此,我创建了一个小的启动程序,该程序使用您的自定义JPanel作为内容窗格创建了一个JFrame ...

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);
    }
}

... and it works as expected. ...并且按预期工作。

So, the problem lies elsewhere. 因此,问题出在其他地方。 Either in the creation of the panel, or its interoperation with other code, or with its expected behaviour. 面板的创建,与其他代码的互操作或预期行为。

First, creation. 首先,创造。 Swing components should only ever be created on Swing's Event Dispatching Thread (EDT). 仅应在Swing的事件调度线程(EDT)上创建Swing组件。 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. 如果在main方法创建应用程序的UI时未使用SwingUtilities.invokeAndWait(...)SwingUtilities.invokeLater(...) ,则可能会将Swing置于错误状态。

Second, interoperation with other code. 第二,与其他代码的互操作。 You've called setFocusable(true); 您已调用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. 但是,如果框架中有多个可聚焦组件,则焦点可能会由另一个UI元素获取。 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. 如果矩形开始响应箭头键,则仅在该帧可见后,您GameseetingGameseeting面板上调用requestFocusInWindow()

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. 如果您按下数字键盘上的UP箭头,则可能期望矩形响应VK_UP代码而移动,但不会。 The code would need to test for the VK_NUMPAD8 code. 该代码将需要测试VK_NUMPAD8代码。

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. 如果您简化了将代码发布到StackOverflow的代码,则可能无意中删除了问题代码。 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. 如果以上提示对您没有帮助,您将需要编辑您的帖子以添加更多信息(和代码),以便我们复制问题并提出解决方案。

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 . 我必须添加上面的启动器代码来创建和测试您的自定义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. 例如,您可以删除VK_UPVK_LEFTVK_DOWN代码,仅VK_RIGHT代码。 That is a minimization, which could still leave the code "Complete". 这是一个最小化,仍然可以保留代码“ Complete”。 But removing the construction of the JPanel does not leave you with a complete example. 但是,删除JPanel的构造并不能为您提供完整的示例。 Test the code that you post, and make sure that it still demonstrates the problem; 测试您发布的代码,并确保它仍然可以解决问题; otherwise we can only guess at the real problem. 否则我们只能猜测真正的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM