无法从控制器填充表单控件

时间:2019-01-08 17:02:54

标签: javafx

首先,我的Maven文件,因为不确定我是否正在使用最新版本的JavaFX:

<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>11</version>
</dependency>
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-fxml</artifactId>
    <version>11</version>
</dependency>

我的 main 方法(只是概念证明:

    @Override
    public void start(Stage primaryStage) {

        Clinica c = new Clinica();
        c.setNombre("Nombre");
        c.setCodigoPostal("CP");
        c.setPoblacion("Malaga");
        c.setDireccion("Calle Se");
        try {

            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("Sample.fxml"));
            SampleController sc=new SampleController();
            sc.setClinic(c);
            loader.setController(sc);
            Parent root = loader.load();
            Scene scene = new Scene(root, 800, 600);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

            primaryStage.setScene(scene);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

我的控制器:

public class SampleController implements Initializable {

    @FXML
    private TextField name;
    @FXML
    private TextField zip;
    @FXML
    private TextField town;
    @FXML
    private TextField address;



    private Clinica c;

    public SampleController() {
    }

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {

        this.name = new TextField(this.c.getNombre());
        this.zip = new TextField(this.c.getCodigoPostal());
        this.town = new TextField(this.c.getPoblacion());
        this.address = new TextField(this.c.getDireccion());
    }

    public void setClinic(Clinica c) {
        this.c = c;

    }

}

还有我的FXML文件:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 
    Do not edit this file it is generated by e(fx)clipse from ../src/main/resources/es/ortoplus/migration/Sample.fxgraph
-->

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

<GridPane xmlns:fx="http://javafx.com/fxml" vgap="5" hgap="5" alignment="CENTER">

    <children>
        <TextField id="name" GridPane.rowIndex="1" GridPane.columnIndex="1"/> 
        <TextField id="zip" GridPane.rowIndex="2" GridPane.columnIndex="1"/> 
        <TextField id="town" GridPane.rowIndex="3" GridPane.columnIndex="1"/> 
        <TextField id="address" GridPane.rowIndex="4" GridPane.columnIndex="1"/> 
    </children>
</GridPane>

问题:我无法填充表单。

我尝试了不在初始化方法中创建实例,期望绑定和注入是自动完成的,但在执行initialize方法时所有控件都为空(所以我有NPE)。

然后,如代码所示,我手动初始化字段并设置值,但是窗体显示为空,并且视图和控制器之间似乎没有绑定。

我在做什么错了?

0 个答案:

没有答案