我想询问用户的性别。我想创建一个文本框,他们可以在其中回答问题。do-while 循环是为了确保他们回答“男孩”或“女孩”。没有错误,但不会运行。
注意我有所有必要的导入...
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);
}
}
最佳答案
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 循环并停留在那里。它永远不会到达绘制窗口和组件的地步。这就是它不运行的原因。
关于java - 带数据验证的文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34426480/