public class GUI
extends JFrame {
private BufferedImage background;
private Point position_ship;
private BufferedImage ship;
public static byte speed = 5;
public static ArrayList<Shot> shots = new ArrayList<Shot>();
public GUI() {
... //GUI Config und Bilder laden
addKeyListener(new MyMoveListener());
addKeyListener(new MyShotListener());
new Repainter(this).start();
}
/**
* Zeichnet die Gegner, Schüsse, Hintergrund und das Schiff
* @param g
*/
@Override
public void paint(Graphics g) {
if (background != null) {
g.drawImage(background, 0, 0, this);
}
if (position_ship != null && ship != null) {
g.drawImage(ship, position_ship.x, position_ship.y, this);
}
g.setColor(Color.WHITE);
for (Shot shot : shots) {
int x = shot.getX(), y = shot.getY();
g.drawLine(x, y, x, y + Shot.LENGTH);
}
}
private class MyShotListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_SPACE) {
return;
}
//Neuer Schuss wird erzeugt
Shot shot = new Shot(new Point(position_ship.x + 25, position_ship.y - Shot.LENGTH), false);
shots.add(shot);
}
}
private class MyMoveListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_SPACE) {
move(e.getKeyCode());
}
}
/**
* Setzt die Position vom Schiff um
* @param keyCode
*/
private void move(int keyCode) {
...
}
}
/**
* Autorepainter
* Zeichnet 10x in der Sekunde die GUI neu
*/
private class Repainter extends Thread {
private final GUI gui;
public Repainter(GUI gui) {
this.gui = gui;
}
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
}
gui.repaint();
}
}
public static void main(String[] args) {
new GUI().setVisible(true);
}
}