1

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!

AJNeufeld
  • 8,526
  • 1
  • 25
  • 44
Usman
  • 123
  • 8
  • You call a function `repaint();` in your `actionPerformed` but I don't see that function anywhere? – Liora Haydont Apr 16 '18 at 17:48
  • As a side note, class names should always begin with a capital letter. See the [Java Naming Conventions](http://www.oracle.com/technetwork/java/codeconventions-135099.html). – Logan Apr 16 '18 at 17:51
  • Which color are you using to color your rectangle (and the background)? What happens when you add breakpoints in your methods or `System.out.println()` statements to see the content of your variables? Do they change? Do they stay the same? Do the methods gets called as expected? Or are they not? – Progman Apr 16 '18 at 18:43
  • Possible duplicate of [How to repaint a JPanel after have drawn on it?](https://stackoverflow.com/questions/4392722/how-to-repaint-a-jpanel-after-have-drawn-on-it) – jobnz Apr 17 '18 at 05:40

1 Answers1

0

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

... 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). 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.

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.

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.

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.

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.

AJNeufeld
  • 8,526
  • 1
  • 25
  • 44