I created a simple Java GUI word game.
It starts of with a head, and the user tries to guess the word. If it is right, the system prints out correct. If it is wrong, it will print out "wrong" and draw a body. The top text box is the hidden word (not really hidden) and the bottom is where you insert your guess.
What is wrong with this program is, the body is not painted after the user guess the wrong word.
The first class:
package hangman;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class NewClass extends JPanel {
int lineA, lineB, lineC, LineD;
int guess;
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.ORANGE);
//head
g.drawOval(110, 10, 25, 25);
g.drawLine(lineA, lineB, lineC, LineD);// (ideal) 125, 40, 120, 100
}
public void newPaint(int a, int b, int c, int d) {
lineA = a;
lineB = b;
lineC = c;
LineD = d;
super.revalidate();
}
}
The second class: package hangman;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class NewClass1 extends JFrame {
private JTextField answerBox, hiddenAnswer;
NewClass nc = new NewClass();
public NewClass1() {
hiddenAnswer = new JTextField();
hiddenAnswer.setText("hat");// this is the word for the hangman
answerBox = new JTextField("put you answer in here");
answerBox.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals(hiddenAnswer.getText())) {
System.out.println("you got it right");
} else {
System.out.println("sorry you got it wrong");
nc.newPaint(125, 120, 40, 100);
}
}
});
add(BorderLayout.NORTH, hiddenAnswer);
add(BorderLayout.SOUTH, answerBox);
}
}
entry point
NewClass1 ncc = new NewClass1();
NewClass nc = new NewClass();
ncc.add(BorderLayout.CENTER,nc);
ncc.setVisible(true);
ncc.setSize(300,300);
ncc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}