我正在尝试使用Swing类和Graphics类来为我拥有的APCS类创建一个子手游戏。
我创建了一个JButton,它将接受用户输入的猜测并将其添加到“未命中”或填写单词中的所有相应字母。我有一个单独的txt文件,可从中选择一个随机单词。
当我运行程序时,所有组件都会显示出来,但是按钮没有任何作用。我已经为此工作了几天,不知道我在做什么错。我最近才刚刚学会如何使用Swing类,所以就我所知这可能是一个愚蠢的错误。我将所有代码都放在下面。
public class Hangman extends JFrame {
DrawPanel panel = new DrawPanel();
Graphics g = panel.getGraphics();
JTextField guess;
JTextField outputWord;
JTextField missesString;
boolean play;
JButton button = new JButton();
String output = "";
String word;
int misses = 0;
public Hangman() {
int again = 0;
String[] dictionary = new String[1000];
In words = new In("words.txt");
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
app.setSize(500, 500);
for (int i = 0; i < 1000; i++) {
dictionary[i] = words.readLine();
}
do {
int num = (int) (Math.random() * 1000);
word = dictionary[num].toLowerCase();
String answer = word;
word = "";
for (int i = answer.length(); i > 0; i--) {
word = word + "*";
}
int length = answer.length();
app.setLayout(new BorderLayout());
JLabel letter = new JLabel();
letter.setFont(new Font("Arial", Font.BOLD, 20));
letter.setText("Enter Your guess");
guess = new JTextField(10);
JLabel output = new JLabel();
output.setFont(new Font("Arial", Font.BOLD, 20));
output.setText("The Word is");
outputWord = new JTextField(30);
outputWord.setText(word);
outputWord.setEditable(false);
JLabel misses = new JLabel();
misses.setFont(new Font("Arial", Font.BOLD, 20));
misses.setText("Misses:");
missesString = new JTextField(52);
missesString.setEditable(false);
button = new JButton("Guess");
button.addActionListener(new ButtonListener());
JPanel panels = new JPanel();
panels.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.add(letter);
panel1.add(guess);
panel1.add(button);
JPanel panel2 = new JPanel();
panel2.add(output);
panel2.add(outputWord);
JPanel panel3 = new JPanel();
panel3.add(misses);
panel3.add(missesString);
app.add(panel1, BorderLayout.NORTH);
app.add(panel2, BorderLayout.EAST);
app.add(panel3, BorderLayout.SOUTH);
app.add(panels);
app.setVisible(true);
again = JOptionPane.showConfirmDialog(null, "Do you want to play again?");
} while (again == JOptionPane.YES_OPTION);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == guess) {
output = "";
}
for (int i = 0; i <= word.length() - 1; i++) {
if (guess.getText().equalsIgnoreCase(word.substring(i, i + 1))) {
output = output.substring(0, i) + guess + output.substring(i + 1, word.length() - 1);
outputWord.setText(output);
} else {
misses++;
missesString.setText(missesString.getText() + guess + " ");
}
}
}
}
}
这些组件可以完美地显示在屏幕上,只是按钮使我无法按预期工作,因此很麻烦。