我想问用户他们的性别。我想创建一个他们可以回答问题的文本框。执行循环是为了确保他们回答" boy"或"女孩"。没有错误,但它不会运行。
注意我有所有必要的进口......
public class Culminating_JavaFX extends Application {
String gender;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
@Override
public void start(Stage primaryStage) throws Exception {
GridPane grid = new GridPane();
TextField textField = new TextField ();
do
{
textField.setPromptText("Are you a boy or a girl?");
textField.setText("");
gender = br.readLine().toLowerCase();
}
while (!(gender.equals("boy")) && !(gender.equals("girl")));
GridPane.setConstraints(textField, 0, 1);
grid.getChildren().add(textField);
}
public static void main(String [] args) {
launch(args);
}
}
答案 0 :(得分:2)
public class Culminating_JavaFX extends Application {
private GridPane grid = new GridPane();
private TextField textField = new TextField();
private Label label = new Label("Are you boy or girl?");
private Button btn;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
btn = new Button();
btn.setText("Answer");
// set action listener -> runs when button is pressed
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
// process the form
process();
}
});
// set constraints
GridPane.setConstraints(textField, 0, 0);
GridPane.setConstraints(label, 0, 1);
GridPane.setConstraints(btn, 0, 2);
// add components to grid
grid.getChildren().add(textField);
grid.getChildren().add(label);
grid.getChildren().add(btn);
// show scene
primaryStage.setScene(new Scene(grid, 300, 250));
primaryStage.show();
}
private void process() {
// get text
String text = textField.getText();
// process text
if (text.equals("boy")) {
label.setText("You are a boy.");
} else if (text.equals("girl")) {
label.setText("You are a girl.");
}
}}
我写了一个简短的例子,请在上面查看。你的程序进入do-while循环并保持在那里。它永远不会达到绘制窗口和组件的程度。这就是它不运行的原因。
答案 1 :(得分:0)
另一方面,请确保从现在开始尝试将逻辑代码和图形用户界面代码尽可能分开。永远不要试图把所有东西塞进GUI类。
接下来的事情是,GUI的一般概念是它们的逻辑在运行之前不能被包含在循环中。当您的程序运行并调用start()
时,它将继续向下执行代码并需要命中一行window.show();
。这将向用户显示窗口。如果您的程序卡在上面的循环中,它将无法向用户显示GUI,因此无法工作。
相反,重新考虑您的计划将如何运作。由于用户需要选择男孩或女孩,为什么不使用ChoiceBox,或者更好,RadioButton。让用户选择他们想要的选项,然后可能有一个Button
让他们点击提交或让ChoiceBox
或RadioButton
通过调用来监听更改:
yourRadioButton.setOnAction(e ->
{
/*
* Set the Boy Girl value here by calling
* yourRadioButton.getValue()
*/
}