I'm asking because I want the addShot()
method in my GamePanel
class to be called when the user hits enter," this initializes a shot object representing a missile fired from a ship, but it doesn't do anything. Is there a visibility issue here, or did I just structure the key event and listener relationship wrong? I'm only posting relevant code, but I can post the rest if necessary.
Here's the code:
public static class GameTest extends JFrame {
private static final int WINDOW_WIDTH = 800;
private static final int WINDOW_HEIGHT = 500;
public GamePanel gamePanel;
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);
} // end constructor
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) {
switch (e.getKeyCode()) {
case KeyEvent.VK_A:
Launcher.lRun = -20;
gamePanel.move(gamePanel);
break;
case KeyEvent.VK_D:
Launcher.lRun = 20;
gamePanel.move(gamePanel);
break;
case KeyEvent.VK_ENTER:
gamePanel.addShot();
break;
default:
Launcher.lRun = 0;
}
}//end keyPressed method
@Override
public void keyReleased(KeyEvent e) {
}//end empty keyReleased method
}//end aKeyListener class
}//end GameTest class
Useful links:
Edit
For example: