I'm trying to make a movable object in a Java frame by pressing the arrow keys. Somehow my animation isn't doing anything, neither is it showing the keyCode (if I would be pressing the wrong keys) through a System.out.println().
Here's my code, I'm hoping someone can look through it, maybe test it out himself and figure out where the problem's located for me? I would be very grateful, cause I'm stuck with this for hours now :(
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GUI extends JPanel implements ActionListener, KeyListener{
Timer tm = new Timer(5, this);
int x = 0, y = 0, velX = 0, velY = 0;
public GUI(){
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, y, 30, 30);
}
public void actionPerformed(ActionEvent e){
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e){
int c = e.getKeyCode();
if(c == KeyEvent.VK_LEFT){
velX = -1;
velY = 0;
}
else if(c == KeyEvent.VK_UP){
velX = 0;
velY = -1;
}
else if(c == KeyEvent.VK_RIGHT){
velX = 1;
velY = 0;
}
else if(c == KeyEvent.VK_DOWN){
velX = 0;
velY = 1;
}
else System.out.println(e.getKeyChar() + " = " + c);
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args){
GUI t = new GUI();
JFrame jf = new JFrame();
jf.setTitle("Animation");
jf.setSize(600,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
}
In your
main
method, add theJPanel
to theJFrame
before callingsetVisible
: