I’m using Graphics2D with java and I want to reset the game if the alien ship hit my ship.
I tried some different things but didn’t worked.
Here’s the JFrame class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame {
public Window() {
add(new Screen());
setTitle("Square Invaders!");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(900, 560);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public static void main(String[] args) {
new Window();
}
}
Here’s the part of the code where I check if the game ended which resides in the
Sceen.java class (extends JPanel):
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g);
if (ingame) {
if (spaceShip.isVisible()) {
drawSpaceShip(g);
}
drawAlienShip(g);
g2d.setColor(Color.white);
g2d.drawString("Squares left: " + aliens.size(), 5, 15);
} else {
String msg = "Game Over";
Font small = new Font("Viner Hand ITC", Font.BOLD, 36);
FontMetrics metr = this.getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (S_WIDTH - metr.stringWidth(msg)) / 2,
S_HEIGHT / 2 - metr.getHeight());
}
g.dispose();
}
I tried to do this(by adding the : new Window()):
g.drawString(msg, (S_WIDTH - metr.stringWidth(msg)) / 2,
S_HEIGHT / 2 - metr.getHeight());
new Window();
}
g.dispose();
}
the result is a window after window is being created !