我在Javafx GUI中创建了一个文本冒险游戏。我向用户显示一个问题,询问用户在Text对象中的名称,然后在其下方显示一个TextField,供用户输入其名称。这些对象位于Vbox中。当用户按Enter键时,我使用事件处理程序从TextField获取文本。一旦给出了名字和姓氏,Text对象应该如下所示,
下面的已清除文本字段你的名字是什么? 乔
你的姓氏是什么? 布罗格斯
欢迎...
在用户输入姓氏之前,这可以正常工作。它不是像使用名字一样在下面添加姓氏,而是将名字改为姓氏,并且不会添加姓氏或下一行(欢迎...):
你的名字是什么? Bloggs
你的姓氏是什么?
我在start()方法中创建TextField和Text对象,并将它们作为参数传递给一个新类,从而启动游戏:
game = new Game();
game.play(textField, text, vbox);
public class Game {
private String firstname;
private String surname;
private TextProcessing textProcessing;
private String currentText;
private String nextText;
public Game() {
firstname = "";
surname = "";
textProcessing = new TextProcessing();
currentText = "";
nextText = "";
}
public void play(TextField textField, Text text, VBox vbox) {
//Get the user's first name.
text.setText("What is your first name?");
currentText = text.getText();
nextText = "\nWhat is your surname?";
firstname = textProcessing.processText(textField, text,
currentText, nextText, vbox);
//Get the user's last name.
if(!firstname.equals("")) {
currentText = text.getText();
nextText = "\nWelcome!";
surname = textProcessing.processText(textField, text,
currentText, nextText, vbox);
}
}
}
public class TextProcessing {
private String userInput;
private String textToDisplay;
public TextProcessing() {
userInput = "";
textToDisplay = "";
}
public String processText(TextField textField, Text text, String
currentText, String nextText, VBox vbox) {
textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent key) {
if (key.getCode() == KeyCode.ENTER) {
vbox.getChildren().remove(text);
userInput = textField.getText();
textToDisplay = currentText + "\n" + userInput + "\n" +
nextText;
textField.clear();
text.setText(textToDisplay);
vbox.getChildren().add(text);
vbox.getChildren().remove(textField);
vbox.getChildren().add(textField);
}
}
});
return userInput;
}
游戏类中的firstname字段未经过更新 firstname = textProcessing.processText(textField,text,currentText,nextText,vbox);声明,因此if语句永远不会成立。我认为我很可能无法理解EventHandler的工作方式 - 我希望它执行一次并返回更新后的值,然后在调用surname = textProcessing.processText(textField, text,currentText,nextText,vbox);我花了好几个小时在这上面,并试图寻找可能对我有帮助的问题,但我还没有能够弄清楚如何让它发挥作用。对此的任何帮助将不胜感激。