简体   繁体   English

我如何制作一个将在 javaFx 中显示 8 个文本字段的 for 循环

[英]How can I make a for loop that will display 8 TextFields in javaFx

This is currently the code that I have so far...这是目前我拥有的代码......

int nums = 8;
for (int j = 0; j < nums; j++) {
   TextField test = new TextField();
   test.setAlignment(Pos.CENTER);
}
this.getChildren().add(test);

I have tried doing somehting like TextField 'test' + j = new TextField();我试过做一些像 TextField 'test' + j = new TextField(); 这样的事情。 so that it would create test1, test2, test3 ect.这样它就会创建 test1、test2、test3 等。 but that gave syntax errors.但这给了语法错误。 Not really sure on how I would go about this in any other way.不太确定我将如何以任何其他方式解决这个问题。

You have to move this.getChildren().add(test);你必须移动this.getChildren().add(test); inside the for -loop:for循环内:

int nums = 8;
for (int j = 0; j < nums; j++) {
   TextField test = new TextField();
   test.setAlignment(Pos.CENTER);
   this.getChildren().add(test);
}

Add them to something that allows them to stack vertically.将它们添加到允许它们垂直堆叠的东西中。 Also, make sure your call to add them is inside the loop where test is still in scope.此外,请确保您对添加它们的调用位于test仍在范围内的循环内。

VBox box = new VBox(5);
int nums = 8;
for (int j = 0; j < nums; j++) {
   TextField test = new TextField();
   test.setAlignment(Pos.CENTER);
   box.getChildren().add(test);
}
this.getChildren().add(box);

@Dustin R's answer is great. @Dustin R 的回答很棒。 I am just adding more.我只是添加更多。 Like how to any an event on each TextField created.就像如何在每个创建的TextField创建任何事件一样。

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class TestingGroundsTwo extends Application
{
    public static void main(String[] args)
    {
        launch(args);
    }

    @Override
    public void start(Stage stage)
    {
        VBox root = new VBox();

        for (int i = 0; i < 8; i++) {
            TextField tempTextField = new TextField();//Create the TextField.
            final int t = i;
            tempTextField.setPromptText("I am TextField " + t);//Set prompt text to easily identify TextField
            //Create key handlding event on the TextField
            tempTextField.setOnKeyReleased((event) -> {
                System.out.println("You typed " + event.getCode() + " in TextField " + t + ". My text value is " + tempTextField.getText());
            });
            root.getChildren().add(tempTextField);//Add the TextField to a parent node. In this case VBox.
        }

        Platform.runLater(() -> root.requestFocus());
        stage.setTitle("Hello World!");
        Scene scene = new Scene(root, 750, 600);
        scene.setFill(Color.GHOSTWHITE);
        stage.setScene(scene);
        stage.show();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM