I am making a basic Hangman game and this is my first time using JFrames and DrawWindows in Java. Here is where my confusion lies:
//This initializes my window and a panel as global variables:
JFrame window = new JFrame("Let's play hangman!");
DrawWindow panel = new DrawWindow();
//This sets up my window and adds the panel to it:
public HangmanTwo() {
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBackground(Color.white);
window.setSize(500, 500);
window.add(panel);
window.setVisible(true);
}
//This next parts draws the head onto the window:
public class DrawWindow extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawRect(50, 50, 75, 400);
g.setColor(Color.lightGray);
g.fillRect(50, 50, 75, 400);
g.drawRect(100, 50, 150, 50);
g.fillRect(100, 50, 250, 50);
//Draws noose and head
g.setColor(Color.black);
g.fillRect(250, 100, 1, 75);
g.drawOval(220, 175, 60, 60);
g.fillOval(220, 175, 60, 60);
}
}
Now, when the person gets their second incorrect guess, I wanted to just be able to add the body onto the head. However, when I try to add both on:
...
} else if (score == 2) {
printOutScore(2, 4);
DrawHead head = new DrawHead();
DrawBody body = new DrawBody();
window.add(head);
window.add(body);
window.setVisible(true);
} else if (score == 3) {
...
It only shows the body and the whole head disappears. Because of this, unfortunately, when I draw the body, I have to REDRAW the head, which you can imagine, when I have to write this 10 times for the easy level (which includes head, body, left arm, right arm, left leg, right leg, top hat, pipe, tie, and a shot of brandy) my code is getting ridiculously long. So now my function class to draw the body looks like this: (the DrawHead plus some body code):
public class DrawBody extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
/*Draws wood structure to start
g.setColor(Color.black);
g.drawRect(50, 50, 75, 400);
g.setColor(Color.lightGray);
g.fillRect(50, 50, 75, 400);
g.drawRect(100, 50, 150, 50);
g.fillRect(100, 50, 250, 50);
//Draws noose and head
g.setColor(Color.black);
g.fillRect(250, 100, 1, 75);
g.drawOval(220, 175, 60, 60);
g.fillOval(220, 175, 60, 60);
//Draws body
g.drawRect(245, 235, 10, 120);
g.fillRect(245, 235, 10, 120);
}
}
Can anyone please help me figure out how I could do it smarter? I can't figure out how to just call DrawHead in DrawBody and so on. Any help would be much appreciated!!
Saludos!