JavaFX Controller未初始化UI字段

我正在通过Scene Builder开发JavaFX项目.
我创建了一个很长的FXML文件(我只报告了一个片段)和关联的控制器.此外,我编写了Application类:

public class Main extends Application {
    @Override
    public void start(Stage stage) {
        Parent root;
        try {
            root = FXMLLoader.load(getClass().getResource("myfxml.fxml"));
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        Scene scene = new Scene(root);

        stage.setTitle("Popolamento dati Ambasciata");
        stage.setScene(scene);
        stage.show();
    }

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

FXML:

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

<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<GridPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="1150.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.FXController">
    ...
<children>
        <Button id="addobject" mnemonicParsing="false" onAction="#addobject" text="Add Object" GridPane.columnIndex="1" GridPane.halignment="CENTER" GridPane.rowIndex="10" />
        <TextField id="objectname" GridPane.columnIndex="1" GridPane.columnSpan="2" GridPane.rowIndex="1" />

控制器:

public class FXController {

@FXML Button addobject;
@FXML TextField objectname;

@FXML
public void addobject() {
    objectname.getText();
}
}

}

该应用程序正确启动,并调用了事件处理程序,但是在访问TextField对象名时,它为null.
我在哪里做错了?

解决方法:

您应该使用fx:id属性而不是id.

如果您查看文档here

Assigning an fx:id value to an element creates a variable in the document’s namespace that can later be referred to by variable dereference attributes

请注意,您仍然可以使用idattribute:

Additionally, if the object’s type defines an “id” property, this value will also be passed to the objects setId() method.

因此,在您的情况下:

<Button fx:id="addobject" ... />
<TextField fx:id="objectname" ... />
上一篇:网络协议之bt---bt协议详解 DHT篇(下)


下一篇:java-如何在MVC架构中使用线程?