KeyListener not working (requestFocus not fixing it)

后端 未结 3 1914
说谎
说谎 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: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

提交回复
热议问题