java—如何将键绑定方法移到自己的类中?

g0czyy6m  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(356)

我正在制作一个游戏,并且在我的gamepanel类中使用了keybindings。不过,我希望能够将我的key bindings方法放在它自己的独立类中,这样游戏的其他面板就可以访问该方法,所以我不必每次都重写它。如您所见,我已经将其移到了上面,但是在调用addkeybinding方法的行中出现了一个空指针异常。我想这跟不知道该怎么做有关?但我不确定。我怎样才能解决这个问题?
游戏面板类:

public class GamePanel extends JPanel implements ActionListener {
    // Global Variables
    private Ball ball;
    private Paddle paddle;
    private GameFrame gameFrame;
    private int width;
    private int height; 
    private Timer timer;
    private int brickHeight = 30;
    private int brickWidth = 60;
    ArrayList<Bricks> brickArray = new ArrayList<Bricks>();
    int brickCount;
    int leftOverSpace;
    private int ballXDir = -1;
    private int ballYDir = -2;
    private boolean play = false;
    private int delay = 8;
    private KeyBindings kBindings;

    // create a constructor
    GamePanel (int gamePanelWidth, int gamePanelHeight) {
        this.setWidth(gamePanelWidth);
        this.setHeight(gamePanelHeight);
        initialiseGame();
        this.isVisible();
    }

    private void initialiseGame() {
        play = false;
        ball = new Ball(10, 520, 30, 30, this); //create the ball object
        paddle = new Paddle(this, 50, 700, 100, 10); //creates paddle object
        initialiseBrickArray();

        //initialise key bindings for space, left and right
        kBindings.addKeyBinding(this, KeyEvent.VK_SPACE, "startBall", (evt) -> {
            play = true;
        });
        kBindings.addKeyBinding(this, KeyEvent.VK_LEFT, "moveLeft", (evt) -> {
            paddle.moveLeft();
        });
        kBindings.addKeyBinding(this, KeyEvent.VK_RIGHT, "moveRight", (evt) -> {
            paddle.moveRight();
        });       
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
    }  
}

我的新keybindings类:

public class KeyBindings implements ActionListener {

    public void addKeyBinding(JComponent comp, int keyCode, String id, ActionListener actionListener) {
        InputMap im = comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap ap = comp.getActionMap();

        im.put(KeyStroke.getKeyStroke(keyCode, 0, false), id);
        ap.put(id, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                actionListener.actionPerformed(e);
            }
        });

        return;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }

}
4dbbbstv

4dbbbstv1#

你应该初始化 kBindings 在构造函数中或其他地方,但在调用 kBindings.addKeyBinding . 只是

kBindings = new KeyBindings();
7gcisfzg

7gcisfzg2#

首先,keybindings类不需要实现actionlistener。实际上,您并没有将此类的示例作为actionlistener添加到按钮中。这只是一个带有方便方法的类。
实际上,您并没有更改keybindings类的任何属性。所以这应该只是类的静态方法:

//public void addKeyBinding(...)
public static void addKeyBinding(...)

然后调用它:

//kBindings.addKeyBinding(...);
KeyBindings.addKeyBinding(...);

相关问题