我创建了一个简单的 Java GUI 文字游戏。
它从一个头开始,用户尝试猜测这个词。如果正确,则系统打印出正确的。如果是错误的,它会打印出“错误”并绘制一个身体。顶部的文本框是隐藏的单词(不是真正隐藏的),底部是您插入猜测的位置。
这个程序的问题是,在用户猜错单词后,身体没有被画出来。
第一课:
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();
}
}
第二类:包刽子手;
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);
}
}
入口点
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);
}
}