问题
Here is what's inside my keyPressed
:
public class Movie extends JFrame implements KeyListener {
public static Sprite star1 = new Sprite("Assets/star1.png");
public static Sprite star2 = new Sprite("Assets/star2.png");
public static Sprite star3 = new Sprite("Assets/star3.png");
public void init(){
this.addKeyListener(this);
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) {
System.out.println("KEY PRESSED: " + e.getKeyChar());
animation window = new animation(500, 450); //length , height
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
setFocusable(true);
Movie.star1.setPosition( Movie.star1.getXposition() -100, 0);
window.frameFinished();
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
setFocusable(true);
Movie.star1.setPosition( Movie.star1.getXposition() +100, 0);
window.repaint();
}
}
My object does not move when the arrow keys are pressed.
All I want to know is - is this because I need to call the keyPressed(KeyEvent e)
method in my main? When I do call it, I get an error that states:
cannot be resolved in a variable
The objects that I want to move are in a giant loop.
回答1:
If you never add the key listener to some Swing component, then it will never receive events.
KeyListener
itself isn't magical and doesn't listen for keypresses. What you do with a KeyListener
is: you tell some other Swing component (like a window or a textbox) to call your KeyListener
when a key is pressed. The component is what looks for keypresses, not the listener.
In your case, it looks like you meant to add the key listener to the window, with this.addKeyListener(this);
(since in your case this
is both a KeyListener
and a JFrame
).
However, if nothing calls your init
method, then the code inside your init
method (like any method) never runs, so the key listener doesn't get added to the window, so the window doesn't call it when a key is pressed!
One possible solution would be to make sure to call init
after creating a new Movie
(you haven't shown the code where that happens).
Another solution would be to use a constructor, instead of a method, like this:
public Movie() {
this.addKeyListener(this);
}
- constructors run when the object is created, so that way, addKeyListener
will be called whenever a Movie
object is created, without the creator having to remember to call init
.
来源:https://stackoverflow.com/questions/30011591/keylistener-do-i-need-to-call-the-keypressed-method-in-my-main