Question

This is my first attempt of using a keylistener in Java, so don't be harsh on me. I am trying to use TimerListener and KeyListener within the same separate private class to supplement the main activities in my upper class.

public class GameMemory { 
    private int[][] grid = new int[24][12]; 
    Figure figure = new Figure(); 

    GameMemory() {
        figure.figureReinitialize();
        Timer timer = new Timer(1000, new TimerListener()); 
        timer.start(); 
    }

And the private class

private class TimerListener implements ActionListener, KeyListener { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
        figure.moveDown(); 
        System.out.println(Arrays.deepToString(grid)); // To debug.
    } 

    @Override
    public void keyPressed(KeyEvent e) { 
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) 
           GameMemory.this.figure.rotateRight(); 
    }

    @Override 
    public void keyReleased(KeyEvent e) { 

    }

    @Override 
    public void keyTyped(KeyEvent e) { 

    }
}

I did an extensive research and watched several online videos and read oracle documentation on the topic, but still can't get much sense out of it. In the current state the code compiles, and timer runs as expected, but I think I am missing a statement somewhere...

I tried addKeyListener in GameMemory constructor, but it said it cannot find symbol.

Any ideas?

Was it helpful?

Solution

If the timer is being called but the key isn't then most likely you haven't added the listener as a KeyListener. That very much looks like what is happening in your code as you put a timer on it but then do nothing else with it.

In general it would be better practice to split them anyway though. Each Java class should try and focus on doing one thing and doing it well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top