user5402685
user5402685

Reputation:

Java Implementing ActionListener methods in Constructor

Im trying to call my keyPressed method that I created (override) in my constructor for a game I am making to allow an object to move. I implemented ActionListener and KeyListener in the main class.

Is this even possible? I tried calling the method by this.keyPressed(KeyEvent e) but I don't know how to initialize e.

What would be the best way to do something like this?

Timer timer = new Timer(DELAY, this);
public Game(Main game) {

    this.game = game;
    gamePanel = new GamePanel();
    buttonPanel = new JPanel();
    buttonPanel.add(startButton);

    this.addKeyListener(this);
    this.setFocusable(true); 
    this.setFocusTraversalKeysEnabled(false);
    this.getContentPane().add(gamePanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
    this.setSize(1000, 1000);
    this.setVisible(true);





    }

}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {

    switch (e.getKeyCode()) {
    case KeyEvent.VK_UP:
        game.move("u");
        break;

    case KeyEvent.VK_DOWN:
        game.move("d");
        break;

    case KeyEvent.VK_RIGHT:
        game.move("r");
        break;

    case KeyEvent.VK_LEFT:
        game.move("l");
        break;
    }
}
@Override
public void actionPerformed(ActionEvent e) {

    Object src = e.getSource();

    if (src == timer) {
        game.updateBoard();
        if (game.gameEnded()) {
            timer.stop();
            }
        repaint();

    } else if (src == startButton) {

        if (timer.isRunning()) {
            timer.stop();
        } else {
            timer.stop();
        }
    }
}

Upvotes: 0

Views: 553

Answers (1)

Judger
Judger

Reputation: 308

The problem is here:

while(!game.gameEnded()) {
    game.updateBoard();
    KeyEvent e = null;
    this.keyPressed(e);
}

If your constructor is called with the Swing Event-Dispatching-Thread, it blocks it, and no event can therefore be dispatched.

The correct way should be using a javax.swing.Timer, which fires an ActionEvent periodically.

int period = 1000;//fire ActionEvent every second
Timer timer = new Timer(period,new ActionListener(){
    public void actionPerformed(ActionEvent e){
        //do your stuff, for example
        game.updateBoard();
    }
});
timer.start();

You shouldn't invoke the methods in EventListener by yourself since they should all be handled by the Event-Dispatching-Thread.

Upvotes: 1

Related Questions