获取JavaFX应用程序主要方法中.fxml文件中定义的TextArea

问题描述 投票:0回答:1

我想问你,是否可以从start()方法中获得我sample.fxml文件中定义的TextArea,在那里我已经定义了FXMLoader和主要阶段。我需要在那里获取TextArea对象,并在其上设置一些我之前保存到文件中的字符串。

谢谢你们!

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/sample.fxml"));
        primaryStage.setTitle("Appilcation");
        primaryStage.setScene(new Scene(root, 420, 330));
        primaryStage.setResizable(true);
        root.getChildrenUnmodifiable().
        // get the TextArea and set text on it which I will get from file
    }

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

这是我的.fxml文件

<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<GridPane fx:controller="sample.PDPController" xmlns:fx="http://javafx.com/fxml" hgap="2" vgap="3" styleClass="root">
    <padding><Insets top="5" right="15" bottom="5" left="15"/></padding>

    <Text id="welcome-text" text="Welcome user!"
          GridPane.columnIndex="0"
          GridPane.rowIndex="0"
          GridPane.columnSpan="1"
          GridPane.halignment="CENTER"
    />

    <Text id="welcome-text-secondary" text="Count data..."
          GridPane.columnIndex="0"
          GridPane.rowIndex="1"
          GridPane.columnSpan="1"
          GridPane.halignment="CENTER"
    />

    <TextArea fx:id="timeInputId" minHeight="200" minWidth="200" wrapText="true"
              promptText="Insert data in specified format." focusTraversable="false"
              GridPane.columnIndex="0"
              GridPane.rowIndex="2"
              GridPane.columnSpan="1"
              GridPane.halignment="CENTER"
    />


    <HBox spacing="10" alignment="bottom_left"
          GridPane.columnIndex="0"
          GridPane.rowIndex="5"
          GridPane.columnSpan="1">
        <Button text="Počítej" onAction="#handleSubmitButtonAction"/>
        <Button text="Ulož" onAction="#handleSaveButtonAction"/>
    </HBox>

    <Text fx:id="actionTarget"
          GridPane.columnIndex="0"
          GridPane.rowIndex="6"
          GridPane.columnSpan="1"
          GridPane.halignment="CENTER"
    />
    <stylesheets>
        <URL value="@../styles.css" />
    </stylesheets>

</GridPane>
java user-interface javafx fxml
1个回答
0
投票

使用forEach循环通过id获取节点,然后将该节点转换为TextArea

 root.getChildrenUnmodifiable().forEach((node) -> {
        if(node.getId()=="timeInputId"){
        TextArea textArea = (TextArea)node;
        textArea.getText();
        }
    });
© www.soinside.com 2019 - 2024. All rights reserved.