I am trying to make a Snake game, the generic old school one, but I'm having some difficulties using keybinding.
After I make an instance of my Gui class, which makes the JFrame, a JPanel and a JPanel array. After this instance I like to use a while loop to check if the player is still alive and if the player is, the snake moves a square every ~1/4 second depending on the difficulty.
When not in the while loop, I can correctly use the keybinding but when I let my program enter the loop, it doesn't recognize me using my buttons.
Maybe this is a standard thing in Java which I do not know about. If it is, can someone show me how I should approach my problem?
InputMap im = base.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = base.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "Right");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Up");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "Down");
am.put("Right", new ArrowAction("Right"));
am.put("Left", new ArrowAction("Left"));
am.put("Up", new ArrowAction("Up"));
am.put("Down", new ArrowAction("Down"));
With the class:
public class ArrowAction extends AbstractAction {
String txt;
public ArrowAction(String txt) {
this.txt = txt;
}
public void actionPerformed(ActionEvent e) {
if (txt.equalsIgnoreCase("Left")) {
System.out.println("The left arrow was pressed!");
keyPressed = 0;
} else if (txt.equalsIgnoreCase("Right")) {
System.out.println("The right arrow was pressed!");
keyPressed = 1;
} else if (txt.equalsIgnoreCase("Up")) {
System.out.println("The up arrow was pressed!");
keyPressed = 2;
} else if (txt.equalsIgnoreCase("Down")) {
keyPressed = 3;
System.out.println("The down arrow was pressed!");
}
}
}
And just a general while loop:
while (alive == true) {
// Some stuff happening, not relevant
}
So why is it that my keybindings do not work inside the loop, but do work outside of it?