我创建了一个简单的 Java GUI 文字游戏。
它从一个头部开始,用户尝试猜测这个单词。如果正确,系统会打印出正确的结果。如果错了,就会打印出“wrong”并绘制一个body。顶部的文本框是隐藏的单词(并非真正隐藏),底部的文本框是您插入猜测的位置。
这个程序的问题是,在用户猜错单词后,主体没有被绘制。
第一个类:
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);
}
}
最佳答案
使用您的newPaint
事件中的API,而不是直接设置NewClass
的字段.
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);
}
编辑:在NewClass1
中,替换repaint()
与 revalidate()
。 Here's the reference .
Edit2:就您而言,最好不要创建 NewClass
NewClass1
外部面板。在 NewClass1
构造函数你可以这样做:
nc = new NewClass();
add(BorderLayout.CENTER, nc);
在添加 hiddenAnswer
之前,然后您可以删除 NewClass
从入口点开始。
问题是,您没有处理 NewClass
的实例您在入口点创建的,您正在使用一个随机的新 NewClass
.
关于带 GUI 的 Java 文字游戏。我的代码有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18724783/