1

I have the following code in Game.java:

public void start ()
{
    Thread thread = new Thread(this);
    thread.start();

    this.world = new World();
}

In the world class, I have the actual items of my game, a set of Walls, food and a player.

public class World {
    private Food food;
    private HashSet<Wall> walls = new HashSet<Wall>();
    private Player player; 
    ...
}

The problem is as follows: I want to have my keylisteners in the player class but I can't seem to figure out how to get this...

I've tried by implementing the KeyListener class in Player.java and implementing the 3 functions that come with that. However, player.java does not allow me to use this.addKeyListener(this) So my keyevents are never triggered...

How can I make this work?

1
  • Is this Swing (a JApplet)? AWT (uses Applet class)? Commented Apr 17, 2011 at 19:37

1 Answer 1

1

You need to call addKeyListener on your Applet / JApplet and pass the (same!) player instance as the listener.

Sign up to request clarification or add additional context in comments.

2 Comments

My goal was to keep everything nice and organised (e.g. only let the Game class talk to the World class and not the underlying Food and Player classes). For this solution (which does work) I have to add a getPlayer() method to the World class, which doesn't seem very clean to me. Or am I still doing something wrong?
You could give the World a method that initializes itself from an Applet (by adding handlers)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.