KeyListener not working (requestFocus not fixing it)

后端 未结 3 1905
说谎
说谎 2020-12-12 02:25

I am trying to make my first game without the help a youtube video. I have watched many youtube series about making java games and they never where what I wanted to do, so a

相关标签:
3条回答
  • 2020-12-12 03:09

    You need to register the keylistener on either your game or panel class. The docs have this to say:

    The listener object created from that class is then registered with a component using the component's addKeyListener method. A keyboard event is generated when a key is pressed, released, or typed. The relevant method in the listener object is then invoked, and the KeyEvent is passed to it.

    So in Panel you could do the following

      public Panel(){
            addKeyListener(this);
        } 
    

    There are other things wrong with your code but this should have input working.

    0 讨论(0)
  • KeyListener should be avoid BECAUSE of it's inherent focus related issues. You never know what might take keyboard focus away from your component.

    Instead, take advantage of the Key Bindings API, which allows you to control the focus level required to trigger your key events.

    It will also allow you to reuse underlying Action associated with the key binding in other places...

    You'd be wise to rename you class Panel to something more meaningful. AWT already has a Panel class and it would be very easy to confuse the two

    0 讨论(0)
  • 2020-12-12 03:22

    KeyListener has 2 big issues, they are binded for all keys and besides component must be focusable and in focus, JPanel is not focusable by default.

    It's strongly dicourage the use of requestFocus see the api.

    Instead of that you can use KeyBindings where you bind a specific key an action.

    You may interested in @camickr blog where he post swing utils things like this Motion using the keyboard.

    Also don't call a class Panel cause it's JPanel parent class name , it's gives to confusion.

    Change this:

    public class Game extends JFrame {
    
    private JFrame frame;
    
    }
    

    to

    public class Game {
    
    private JFrame frame;
    }
    

    Another thing don't implement KeyListener at top level class, instead of that use anonymous classes or private classes you are breaking Single Responsability Principle

    0 讨论(0)
提交回复
热议问题