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 ofKeyListener
for particular key reactions.