I managed to make it work with key binding. However, I also discovered how to do it the way I originally wanted:
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class AsteroidRun extends JFrame{
static Image dbImage;
static Graphics dbg;
Image starfield;
Image spaceship;
private int shipx = 100;
private int shipy = 200;
public class AL extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == e.VK_LEFT){
shipx-=4;
repaint();
}
if(keyCode == e.VK_RIGHT){
shipx+=4;
repaint();
}
if(keyCode == e.VK_UP){
shipy-=4;
repaint();
}
if(keyCode == e.VK_DOWN){
shipy+=4;
repaint();
}
}
}
public AsteroidRun() {
starfield = new ImageIcon(AsteroidRun.class.getResource("Pics/starfield.jpg")).getImage();
spaceship = new ImageIcon(AsteroidRun.class.getResource("Pics/spaceship.png")).getImage();
addKeyListener(new AL());
setTitle("Asteroid Run");
setSize(500,400);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g){
dbImage = createImage(getWidth(),getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage,0,0,this);
}
public void paintComponent(Graphics g){
g.drawImage(starfield,0,0,this);
g.drawImage(spaceship,shipx,shipy,this);
}
public static void main(String[] args){
new AsteroidRun();
}
}
Both ways work, but I prefer the above way. Nevertheless, figuring out key binding was a good learning experience!