My launcher object (represented by a bald eagle picture) for a game I'm making doesn't respond to key events. I know it's an issue with how I'm declaring the listener, but I'm not sure what I'm doing wrong.
Here's my code:
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
GameTest t = new GameTest();
}
public static class GameTest extends JFrame {
private static final int WINDOW_WIDTH = 800;
private static final int WINDOW_HEIGHT = 500;
private GamePanel gamePanel;
private GameTest gameTest;
public GameTest() throws IOException {
super("Deep Fried Freedom");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLayout(new BorderLayout());
gamePanel = new GamePanel();
add(gamePanel);
center(this);
setVisible(true);
this.addKeyListener(new aKeyListener());
this.setFocusable(true);
}
public void center(JFrame frame) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Point center = ge.getCenterPoint();
int w = frame.getWidth();
int h = frame.getHeight();
int x = center.x - w / 2, y = center.y - h / 2;
frame.setBounds(x, y, w, h);
frame.validate();
}//end of center method
public class aKeyListener implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {
}//end empty keyTyped method
@Override
public void keyPressed(KeyEvent e) {
Launcher.lRun -= 5;
gamePanel.move();
}//end keyPressed method
@Override
public void keyReleased(KeyEvent e) {
}//end empty keyReleased method
}//end aKeyListener class
}//end GameTest class
}// end main class
public class GamePanel extends JPanel {
Launcher launcher1;
Background bground1;
public GamePanel() throws IOException {
super();
launcher1 = new Launcher();
bground1 = new Background();
}//end constructor
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bground1.background, 0, 0, getWidth(), getHeight(), null);
g.drawImage(launcher1.baldEagleImage, 350, 415, null);//paint the launcher
}//end paintComponent method
public void move() {
launcher1.moveX();
repaint();
}//end move method
}//end GamePanel class
public class Launcher {
public static int lxCoord; //the launcher's x coordinate
public static final int lyCoord = 415;
public static int lRun = 0; //the launcher's x change
public static BufferedImage baldEagleImage;
//Constructor
public Launcher() throws IOException {
lxCoord = 350;
baldEagleImage = ImageIO.read(new File("baldeagleimage.jpg"));
}
/**
* The movement of the launcher in the x direction
*/
public void moveX() {
lxCoord += lRun;
}//end moveX method
}//end Launcher class
public class Background extends JPanel {
BufferedImage background;
public Background() throws IOException {
background = ImageIO.read(new File("flagbackground.jpg"));
}//end constructor
}//end Background class