i'm trying a simple graphics game. what i want is when player loses, a "game over" message to be displayed and a JButton to be added to the panel. Here is the code:
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawBoard(g);
}
private void drawBoard(Graphics g) {
if(inGame) {
// painting code goes here
}
else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
Font font = new Font("Monospaced", Font.BOLD, 18);
FontMetrics metrics = g.getFontMetrics(font);
g.setColor(Color.WHITE);
g.setFont(font);
String msg = "Game Over";
g.drawString(msg, (B_WIDTH - metrics.stringWidth(msg)) / 2, B_HEIGHT / 2);
JButton btn = new JButton("Again");
add(btn);
btn.setLocation(B_WIDTH/2, B_HEIGHT/2); // not working
revalidate() // drives execution in a recursive loop
}
The problem is that if i put revalidate()
infinite buttons are added. If i dont, no button added. Could someone please explain?
Thanks!
EDIT: I followed MrPk's solution and changed gameOver()
as this:
private void gameOver(Graphics g) {
Font font = new Font("Monospaced", Font.BOLD, 18);
FontMetrics metrics = g.getFontMetrics(font);
g.setColor(Color.WHITE);
g.setFont(font);
String msg = "Game Over";
g.drawString(msg, (B_WIDTH - metrics.stringWidth(msg)) / 2, B_HEIGHT / 2);
if ( !Arrays.asList(getComponents()).contains(btn) ) {
add(btn);
btn.setLocation(100,100);
}
if (Arrays.asList(getComponents()).contains(btn) ) {
System.out.println("added");
System.out.println(btn.getX() + " " + btn.getY());
}
}
When the game ends, the button is still invisible but the program prints :
added
100 100
So, -if i understood right- the problem is that the button is added, but not showing, right? I'd like to know why this happens, and not how to fix this.
thanks again