Reputation: 2616
I am writing a simple java snake-like game, and I ran into a problem even before I actually got to making the game. I can't seem to get input from the keyboard for some reason. My current code is:
public class GameWindow extends JFrame{
private SnakeCanvas snakeCanvas;
public GameWindow(StartWindow sw) {
getContentPane().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
JOptionPane.showMessageDialog(null, "Key Pressed!");
}
});
getContentPane().setBackground(Color.BLACK);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setUndecorated(true);
this.setVisible(true);
getContentPane().setLayout(null);
snakeCanvas = new SnakeCanvas();
snakeCanvas.setBounds(78, 72, 290, 195);
getContentPane().add(snakeCanvas);
snakeCanvas.setVisible(true);
snakeCanvas.repaint();
}
}
(a SnakeCanvas extends JPanel and has no other components on it)
I've tried also adding a key listener to the snakeCanvas and still no effect.. I've also tried to play with the focusable and the focus Traversal stuff but that also didn't do anything... Can anyone please explain to me what I'm doing wrong?
Upvotes: 1
Views: 1159
Reputation: 347214
Make sure you have set the components you want to receive keyboard events is focusable (setFocusable
) & has focus (requestFocus
)
Upvotes: 3
Reputation: 109813
KeyListener isn't proper listener for Swing JComponents, required focus in the window
you have to setFocusable
for container
right and correct way is usage of KeyBindings, for example
Upvotes: 2