Pregunta

I'm making a little game that draws "Game over" at a certain event and I want the player to lose control of the character when this happens. I am using key adapter in a different class and adding it in the constructor, like this:

addKeyListener(new GetKeyStroke(this));

My game over code looks like this (it's in the paint method):

if (gameOver) {
        g.setFont(pauseFont);
        g.setColor(Color.WHITE);
        g.drawString("Game Over!", screenSize.width / 2 - 110, screenSize.height / 5);  
    }

I've tried using

removeKeyListener(new GetKeyStroke(this));

but from what I know, that creates a new object and that's why it doesn't work.

Any help is greatly appreciated

¿Fue útil?

Solución

You'll need some kind of reference variable for the GetKeyStroke you add.

private GetKeyStroke keyListener = new GetKeyStroke(this);
...
addKeyListener(keyListener);

You may also want to have a getter for it, if you want to access it from another class, say something like

public class One {
    private GetKeyStroke keyListener;

    public One() {
        keyListener = new GetKeyStroke(this);
        addKeyListener(keyListener);
    }

    public GetKeyStroke getKeyListener(){
        return keyListener;
    }
}

Then you can pass the One as reference to Two and use the getKeyListener method to get a reference to the same instance GetKeyStoke

public class Two {
    private One one;
    private GetKeyStroke keyListener;

    public Two( final One one ) {
        this.one = one;
        keyListener = one.getKeyListener();
    }

    public someMehod() {
        one.removeKeyListener(keyListener);
    }
}

Maybe more proper designs would be make use of an interface. An example can be seen here and maybe even a more advanced topic of MVC Design may be of future interest to you.


Side Note:

  • As noted in my comment to your original post: Look into using Key Bindings for Swing apps. Often you'll face focus issues with KeyListener. Key Bindings are actually recommended by Oracle over the use of KeyListener for particular key reactions.

Otros consejos

u could create a object as your keylistener

Object a = new GetKeyStroke();

then you can add and remove it.

button.addKeyListener((KeyListener) a);
button.removeKeyListener((KeyListener) a);

Note i am not a expert, i know using Object isnt good, but i just could not figure out what i was supposed to use

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top