KeyListener - do I need to call the keyPressed Method in my main?

两盒软妹~` 提交于 2019-12-06 10:52:22

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!