从具有至少40个文本字段的fxml的文本字段中获取fx:id的好方法是什么? [英] What is a good way to fetch fx:id from a textfield from a fxml with at least 40 textfields

查看:150
本文介绍了从具有至少40个文本字段的fxml的文本字段中获取fx:id的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,我的应用程序需要大约40个独特的文本字段(以及相关的标签)。

I'm running into a problem where I have an application that needs around 40 unique textfields (along with their associated label).

然而,问题我'我遇到的是我想不出一个干净的方法来设置它并在控制器中获取它们的fx:id字段。

However, the problem I'm running into is that I can't think of a clean way to set this up AND get their fx:id fields in the controller.

如果我创建了所有的文本字段并在FXML的HBox中标记,然后我没有办法从控制器获取所有的fx:id,所以目前我只是将ID从FXML复制并粘贴到控制器,然后设置代码来映射文本字段为其ID。这听起来很愚蠢,因为它永远不会缩放,也意味着如果我在FXML上更改fx:id,那么我也必须在控制器中更改它。

If I create all the textfields and label in a HBox in FXML, then I don't have a way to get all the fx:id from the controller and so currently I just copy and paste the id from the FXML to the controller and then set up code to map the Text Field to their id. This sounds stupid as it will never scale and also means if I change a fx:id on the FXML, then I must change it in the controller as well.

是否有一个更好的方法吗?

Is there a better way to do this?

推荐答案

虽然你的问题并不能说明你的最终目标是什么,但其他一些用户建议在Java代码中使用循环来创建 TextFields

While your question does not make it really clear what your end goal is, some other users suggested using a loop in your Java code to create the TextFields.

我同意,因为你所描述的可能是最不适合FXML,因为使用Java代码完成起来要简单得多。

I agree, since what you describe is probably not best suited for FXML as it is much simpler to accomplish using Java code.

以下示例使用名为 TextInput 的自定义数据模型对象,其中包含 TextField 及其关联的标签

The sample below uses a custom data model object called TextInput that contains both the TextField and its associated Label.

代码本身也有额外的见解。

The code itself is also commented with additional insight.


代码

Main.java - 仅用于启动应用程序并显示舞台:

Main.java - Simply used to start the application and show the Stage:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout.fxml"));
            loader.setController(new Controller());

            primaryStage.setScene(new Scene(loader.load()));
            primaryStage.setTitle("Dynamic TextFields Example");
            primaryStage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Layout.fxml - 一个简单的GUI布局,包含 GridPane ,用于显示 TextInput 数据:

Layout.fxml - a simple GUI layout containing the GridPane used to display the TextInput data:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.layout.*?>
<VBox alignment="TOP_CENTER" prefHeight="400.0" prefWidth="300.0" spacing="10.0" xmlns="http://javafx.com/javafx/9.0.1"
      xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <ScrollPane fitToHeight="true" fitToWidth="true" VBox.vgrow="ALWAYS">
            <content>
                <GridPane fx:id="gridPane" hgap="10.0" vgap="5.0">
                    <columnConstraints>
                        <ColumnConstraints hgrow="NEVER" minWidth="-Infinity"/>
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0"/>
                    </columnConstraints>
                    <rowConstraints>
                        <RowConstraints minHeight="-Infinity" prefHeight="30.0" vgrow="NEVER"/>
                    </rowConstraints>
                </GridPane>
            </content>
            <padding>
                <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
            </padding>
        </ScrollPane>
        <Button fx:id="btnGetInputText" mnemonicParsing="false" text="Get Input 4 Text"/>
    </children>
    <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
    </padding>
</VBox>

Controller.java - FXML布局的控制器

Controller.java - the controller for the FXML layout

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;

import java.util.ArrayList;
import java.util.List;

public class Controller {

    @FXML
    private GridPane gridPane;
    @FXML
    private Button btnGetInputText;

    // List of new TextInput objects
    List<TextInput> textInputs = new ArrayList<>();

    @FXML
    private void initialize() {

        // Here we will generate 40 new TextInput objects.
        for (int i = 0; i < 40; i++) {
            TextInput input = new TextInput(
                    "Input " + i,
                    new Label("Input " + i + ":"),
                    new TextField()
            );

            // Now, add the new TextInput Label and TextField to the GridPane
            gridPane.add(input.getLabel(), 0, i);
            gridPane.add(input.getTextField(), 1, i);

            // Finally, add the input to the list so they can be retrieved later using the input's Name
            textInputs.add(input);
        }

        // Use the button to print out the text from Input #4
        btnGetInputText.setOnAction(e -> {
            System.out.println("Input #4: " + getInputTextByName("Input 4"));
        });
    }

    /**
     * Helper method to get the value of a specific TextField
     */
    private String getInputTextByName(String name) {

        // Loop through the list of TextInput objects and get the one with the desired name
        for (TextInput input :
                textInputs) {
            if (input.getName().equalsIgnoreCase(name)) {
                return input.getTextField().getText();
            }
        }

        // If not found, return null (or empty String, if desired)
        return null;

    }
}

/**
 * Custom data structure to hold both the Label and TextFields for your inputs. There is also a Name field that can
 * be any type you wish, but provides a way of locating the right TextField when you need to. This could just as
 * easily be done with an ID or searching label.getText(), but I'm using a separate field in this sample for simplicity.
 */
class TextInput {

    private final String name;
    private final Label label;
    private final TextField textField;

    public TextInput(String name, Label label, TextField textField) {
        this.name = name;
        this.label = label;
        this.textField = textField;
    }

    public String getName() {
        return name;
    }

    public Label getLabel() {
        return label;
    }

    public TextField getTextField() {
        return textField;
    }
}

这篇关于从具有至少40个文本字段的fxml的文本字段中获取fx:id的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆