以下是代码:
public void stage() {
textarea1.setText("You are walking home from a long journey to your castle when you witness a huge explosion!");
textarea1.setText(textarea1.getText() + "\n" + "What do you do?:\n(1)Run into the burning castle\n(2)Attend to the wounded\n(3)Look for the arsonist.");
// need to force user to input text here
if (Integer.parseInt(textfield.getText()) == 1) {
textarea1.setText(textarea1.getText() + "\n" +"You attempt to run into the castle to save the inhabitants but the smoke and heat are too much. You exit the castle.");
textarea1.setText(textarea1.getText() + "\n" + "What do you do?:\n(1)Attend to the wounded\n(1)Look for the arsonist.");
if (Integer.parseInt(textfield.getText()) == 1) {
stage2();
}
if (Integer.parseInt(textfield.getText()) == 2) {
stage3();
} else {
textarea1.setText(textarea1.getText() + "\n" +"Please type the number before the choice you would like and press ENTER");
stage1();
}
}
if (Integer.parseInt(textfield.getText()) == 2) {
stage2();
}
if (Integer.parseInt(textfield.getText()) == 3) {
stage3();
} else {
textarea1.setText(textarea1.getText() + "\n" +"Please type the number before the choice you would like and press ENTER");
stage1();
}
}
基本上我正在写一个游戏,在这个方法的开头,用户有几个选择。用户必须在JTextField
中输入他的选择(1,2或3),并且程序使用一系列if / else语句根据输入转到不同的方法。但是,在运行if / else语句之前,程序不允许用户有时间在JTextField
中输入选项,因此它总是转到else并创建无限循环。如果我用C ++编写,我知道我可以使用系统(暂停),如果我没有在Java中使用Swing,我可以使用扫描类。如何强制我的程序为用户留出时间在JTextField
中输入整数?感谢您的帮助,非常感谢。
答案 0 :(得分:2)
您可以在' ENTER'之后调用if-statements 。被压了。
myComponent.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//insert if-statements
}
});
// do this with all your textfields
答案 1 :(得分:1)
我建议另一种解决方案,为您提供一些先进的功能。还请考虑@ LuxxMiner的答案。
此解决方案使用组合框,如果您被强制使用,则可以将其调整为文本字段。至强>
public class Main extends Application {
@Override public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("LittleGame");
primaryStage.setScene(new Scene(new AnchorPane() {
{
getChildren().add(new ComboBox<String>() {
{
getItems().addAll("Run", "Fight", "Cry!");
setValue("Choose your style");
valueProperty().addListener((observable, oldValue, newValue) -> {
switch (newValue) {
case "Run":
System.out.println("You chose to run, fool!");
//Goto stage run
break;
case "Fight":
System.out.println("You chose to fight!");
//Goto stage fight
break;
case "Cry!":
System.out.println("You chose to cry!");
//Goto stage cry
break;
default:
System.out.println("*This fight style is not available!*");
}
});
}
});
}
}));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
此代码使用匿名类尽可能短,在使用此代码时应使用更结构化的方法:)