I'm trying to make a program that moves a rectangle around the screen when the arrow keys are pressed. At the moment I'm working on keybindings, after KeyListeners proved to be unreliable and fairly useless. Before trying to make the rectangle move, I'm just trying to make the press of the Up arrow key trigger System.out.println("Up key pressed!")
, simply to make sure my KeyBindings are actually working. The problem is, they aren't. I'm following this tutorial, which is a little different from what I'm trying to achieve but should still teach me how to use key bindings. Why does the KeyBinding not work?
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GamePanel extends JPanel implements Runnable{
boolean isRunning = true;
int count = 0;
Thread t;
static int rectX = 250;
static int rectY = 250;
Action upAction;
Action downAction;
Action leftAction;
Action rightAction;
public GamePanel()
{
upAction = new UpAction();
t = new Thread(this);
t.run();
/*downAction = new DownAction();
leftAction = new LeftAction();
rightAction = new RightAction();*/
this.getInputMap().put(KeyStroke.getKeyStroke("UP"), "upMotion");
this.getActionMap().put("upMotion",upAction);
}
public void run()
{
loop();
}
public void loop()
{
if(isRunning)
{
Thread t = Thread.currentThread();
try
{
t.sleep(5);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
repaint();
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
count += 1;
g.drawString(Integer.toString(count), 10, 10);
g.drawRect(rectX, rectY, 50, 50);
loop();
}
static class UpAction extends AbstractAction
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Up key pressed!");
rectY++;
}
}
}
Main JFrame code:
import javax.swing.*;
public class MainFrame{
JFrame frame = new JFrame("Space Invaders");
GamePanel gamepanel = new GamePanel();
public MainFrame()
{
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.add(gamepanel);
}
public static void main(String[] args)
{
new MainFrame();
}
}