I am trying to make a game engine. I have made the Game class but the error resides in the KeyBoard class. Here I leave some code.
Class:: Game
Simply, your panel needs to be focusable. Add in wherever you create the panel:
panel.setFocusable(true);
panel.requestFocusInWindow();
Here's a SSCCE (I suggest asking questions with one of these in the future):
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimpleKeyTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.getContentPane().add(panel);
panel.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Pressed " + e.getKeyChar());
}
});
panel.setFocusable(true);
panel.requestFocusInWindow();
frame.setSize(new Dimension(300, 300));
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Also, https://www.google.com/search?q=jpanel+keylistener
You can add the key listener to the JFrame, that's something I've done in the past. It's probably not a good idea however if you have other components in the JFrame.