unhappycat
unhappycat

Reputation: 416

KeyListener with focus not functioning

I'm adding a key listener to my code, but it is unresponsive. I don't know if this question is redundant, but other questions about a similar issue all say that I should have focus on the component. However, as you can see here, I've tried to do that but it doesn't work. I also have a thread running to render my (very bad) game, which might be an issue, but again, I just simply don't know.

private GamePanel() {

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //get screen dimensions. 

        myImage = new BufferedImage((int) screenSize.getWidth(), (int) screenSize.getHeight(), BufferedImage.TYPE_INT_RGB);
        myBuffer = myImage.getGraphics();
        Player p = new Player(400, 500);
        p.draw(myBuffer);
        abc = new Player(400, 500);
        this.addKeyListener(new Key());
        setFocusable(true);
        this.requestFocus();

    }
public void init() {
    JFrame frame = new JFrame("im bad at coding");
    frame.setLocation(0, 0);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(this);
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setUndecorated(false);
    frame.setVisible(true);
    //ive tried to request focus and set focusable here, but no results
    new Thread(this).start(); 

}

Upvotes: 0

Views: 44

Answers (1)

Joe
Joe

Reputation: 1342

I believe this may be due to either

A) Not initializing your Game object at all when creating the JFrame
B) Not properly embedding your key listener 

Try this:

public static void main(String[] args) {
    GamePanel panel = new GamePanel(); //Call your init methods to initialize the panel only, not the jframe
    //Initialize the key listener object either implemented in the game panel itself, or initialized inside of the panel
    new Thread(panel).start(); 
    JFrame frame = new JFrame("im actually not that bad at coding");
    frame.setLocation(0, 0);
    frame.add(panel);
    frame.addKeyListener(panel.getKeyListener()); //Or addListener, i am doing this not on an IDE
    frame.setDefaultCloseOperation(JFrame.BLOW_UP_SYSTEM_ON_EXIT);
    //Optional, just click the frame: frame.setFocus(true);
    frame.pack();
    frame.setVisible(true);
}

Upvotes: 1

Related Questions