首先,我想我会尝试编写一个没有GUI的标准hangman程序。我能够成功做到这一点。但我无法进入GUI。我似乎最挣扎于GUI。
到目前为止,我将展示我的代码。也许你们可以指出我正确的方向?或者告诉我,我是否走在正确的轨道上?
驱动:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Hangman {
public static void main (String[] args){
JFrame frame = new JFrame ("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
HangmanPanel hmp = new HangmanPanel();
frame.getContentPane().add(hmp);
frame.pack();
frame.setVisible(true);
}
}
Panel Class(这个有点凌乱,因为我正在尝试实验,我猜想我会经历一个试错过程)如果它逻辑上关闭我会道歉。
import java.awt.Panel;
import java.util.Scanner;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class HangmanPanel extends JPanel {
private Hangman hm;
Scanner input = new Scanner(System.in);
final String[] WordList = { "ADA", "COBOL", "LOGO", "BASIC", "PROLOG",
"UBUNTU", "UHURU" };
String ChosenWord = WordList[(int) Math.random() * WordList.length];
StringBuilder display = new StringBuilder(ChosenWord.length());{
for (int i = 0; i < ChosenWord.length(); i++)
display.append("*");
int NumberOfTries = 0;
System.out.print("Let's Begin \n\n");
System.out.println("Try to guess the word in 6 tries, or you're a dead man!\n\n");
boolean correct = false;
while (NumberOfTries < 6 && !correct) {
String UserGuess = input.next();
String Letter = UserGuess.substring(0, 1);
if (ChosenWord.indexOf(Letter) < 0) {
System.out
.printf("The letter %s does not appear anywhere in the word.\n",
Letter);
NumberOfTries++;
}
else {
if (display.indexOf(Letter) >= 0)
System.out
.printf("The letter %s has already been entered as a guess.\n",
Letter);
else {
for (int p = 0; p < ChosenWord.length(); p++)
if (ChosenWord.charAt(p) == Letter.charAt(0))
display.setCharAt(p, Letter.charAt(0));
}
}
correct = display.indexOf("*") < 0;
draw(NumberOfTries);
}
if (correct)
System.out
.println("You have guessed "
+ ChosenWord
+ " correct and saved yourself from the gallos. Till next time that is.\n");
else {
System.out
.printf("You've had %d strikes against you. Thus you've been hung. Better luck next time.\n",
NumberOfTries);
}
}
public static void draw(int num) {
JPanel p1 = new JPanel();
p1.setBorder(BorderFactory.createEtchedBorder());
final String[] status = { "____\n| |\n | \n|\n|",
"____\n| |\n| O\n|\n|\n|", "____\n| |\n| O\n|/|\n|\n|",
"____\n| |\n| O\n|/|\\\n|\n|", "____\n| |\n| O\n|/|\\\n|/\n|",
"____\n| |\n| O\n|/|\\\n|/\\\n|" };
p1.add(new JLabel("Etched Border"));
if (num >= 0 && num < status.length) {
System.out.println(status[num]);
}
else {
System.out.println("Must be a Mistake. Out of Range.");
}
}
}
答案 0 :(得分:1)
Swing(和大多数GUI)是事件驱动的环境。这基本上意味着逻辑的执行通常由事件侦听器/处理程序
处理首先熟悉如何编写一般用户界面,看看Creating a GUI with Swing
使用像while-loop
这样的东西来获取用户输入在GUI环境中不起作用,你需要使用可用的控件构建你想要做的概念