JavaFX-通过场景构建器访问嵌套属性

时间:2018-09-04 20:50:06

标签: javafx

我的应用程序具有以下控制器:

this.countryMap[state.country_id].name

customerPane是扩展的GridPane:

public class Controller {

    @FXML
    private CustomerPane customerPane;

}

我的* .fmxl看起来像(我省略了一些细节):

public class CustomerPane extends GridPane {

    @FXML
    private TableView<Customer> customerTable;

    public CustomerPane() {
        System.out.println(this.customerTable);
    }

}

我在这里遇到两个问题:

  1. 如果使用场景构建器保存fmxl文件,它将覆盖我的CustomerPane的导入。为什么会这样,我该如何解决?

  2. <?import vm.CustomerPane?> <CustomerPane fx:id="customerPane" layoutX="316.0" prefHeight="654.0" prefWidth="536.0" style="-fx-background-color: #7C8184;"> <children> <TableView fx:id="customerTable" editable="true" prefHeight="200.0" prefWidth="461.0" GridPane.columnSpan="2" GridPane.rowIndex="1"> </TableView> </children> </CustomerPane> 导致为空。为什么以及如何解决?

1 个答案:

答案 0 :(得分:0)

使用类作为控制器并使用与该类同名的元素进行创建是不同的。

在您的情况下,您假设Controller的实例用作控制器实例:

创建了一个CustomerPane实例,但是由于它不是控制器,因此该对象的customerTable字段不是目标对象,可以将该对象注入。

您应该尝试使用Custom Component方法:

<?import vm.CustomerPane?>
<fx:root type="vm.CustomerPane" layoutX="316.0" prefHeight="654.0" prefWidth="536.0" style="-fx-background-color: #7C8184;" xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <TableView fx:id="customerTable" editable="true" prefHeight="200.0" prefWidth="461.0" GridPane.columnSpan="2" GridPane.rowIndex="1">
        </TableView>
    </children>
</fx:root>
public class CustomerPane extends GridPane {

    @FXML
    private TableView<Customer> customerTable;

    public CustomerPane() {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxmlpackage/fxmlName.fxml"));
        loader.setRoot(this);
        loader.setController(this);
        try {
            loader.load();
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
        System.out.println(this.customerTable);
    }

}

这允许您使用new CustomerPane()创建实例,或者使用<CustomerPane>元素在fxml中创建一个实例

<CustomerPane/>
相关问题