Domanda

I would like to make a game where a square goes around with the arrow keys, but I am unable to Declare it see moveIt

public void moveIt(/*Won't work here, since its started on run method*/) {


 KeyEvent evt=/*???*/; //how do i declare this keyevent?


 switch (evt.getKeyCode()) {
        case KeyEvent.VK_DOWN:
            myY += 5;
            break;
        case KeyEvent.VK_UP:
            myY -= 5;
            break;
        case KeyEvent.VK_LEFT:
            myX -= 5;
            break;
        case KeyEvent.VK_RIGHT:
            myX += 5;
            break;
    }



}

myX and myY are coordinates for the rectangle to use in another method.

By the way, I'm new to java. Its my first programming language.

È stato utile?

Soluzione

The short answer is that you don't declare a KeyEvent. The KeyEvent is generated by the user pressing a key. That event is then picked up by a KeyListener, where you place your logic to handle the key event.

public class MyClass extends JPanel implements KeyListener
{
    // Add your intialization code here

    @Override
    public void keyTyped(KeyEvent e)
    {
        switch (evt.getKeyCode())
        {
            case KeyEvent.VK_DOWN:
                myY += 5;
                break;
            case KeyEvent.VK_UP:
                myY -= 5;
                break;
            case KeyEvent.VK_LEFT:
                myX -= 5;
                break;
            case KeyEvent.VK_RIGHT:
                myX += 5;
                break;
        }
    }
}

Take a look at this tutorial. You've missed a trick, and reviewing the fundamentals will likely put you back on course.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top