Question

I've been trying to let an image move up and down in Jpanel for quite a long while, but it never seems to work.

If I put "y = y - 1" in the view, it makes the image move up, so I guess the problem is with the keylistener, right?

Could anyone help me with this please? To be honest... I think it will be a very stupid mistake but I can't find how to get it to work.

Extra information: I am using BlueJ to from it, with 4 classes in the basic program for my question. I realize that a lot of people on the internet said to use key bindings and not KeyListener but I don't understand key bindings as for now...

--- Following the advice of Hovercraft Full Of Eels, I will try to use Keybindings. ---

So Keybindings has 2 'commands' to work: input and action.

Copied this code and changed it for my program:

protected void addBindings() {
   int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
   InputMap inputMap = getInputMap(condition); // What does this do?

   KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.KEY_PRESS);
   inputMap.put(key, move(0, 2));

The move function:

protected void beweeg (int dx, int dy)
{
    view.x = view.x + dx;
    view.y = view.y + dy;
}

I have to say... the code system on this forum is incredibly frustrating. When trying this I get: "cannot find symbol - method getInputMap(int)" Did I need to declare it somewhere? I don't see anything about this.

Was it helpful?

Solution

You ask:

When trying this I get: "cannot find symbol - method getInputMap(int)" Did I need to declare it somewhere?

This method must be called on an object that derives from JComponent or one of its children such as a JPanel. This error message means that you're making this call inside of a class that does not extend JComponent or one of its children such as a JPanel. A possible solution is to call the method on the object that you want to attach the bindings to, on your JPanel object.


Speaking of links, here are some of mine: link, link, link, link, link, link,...

OTHER TIPS

Keywords: driving rotating turning car

So after a long time of searching and the help of several forums I got the following result, to 'drive' cars and making 'smooth' turns. Sorry for not using the code provided before, it helped me to understand a lot though. Thanks

I can't figure out how to use the coding on this forum, can anyone insert the following code please? thanks http://hostcode.sourceforge.net/view/1728

Maybe someone will be able to use it putting it online :)

Kind regards

Niels

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top