简体   繁体   English

JavaFX - 可重用的FXML组件

[英]JavaFX - Reusable FXML component

I am building a GUI with Scene Builder, and the majority of my scenes have one element in common (an iOS type home button at the bottom). 我正在使用Scene Builder构建GUI,我的大多数场景都有一个共同的元素(底部是iOS类型的主页按钮)。 I was wondering if it was possible to define this component in a separate fxml file. 我想知道是否可以在单独的fxml文件中定义此组件。 From the research I conducted, there exists a similar process for declaring a reusable component but only within the same fxml file. 根据我进行的研究,存在一个类似的过程,用于声明可重用组件,但仅在同一个fxml文件中。 How could I apply this principle for several fxml files? 我怎么能将这个原则应用于几个fxml文件?

You can do like this: 你可以这样做:

<AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.example.MainController">
<children>
<fx:include fx:id="someId" source="NestedFXML.fxml"/>
</children>

<AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.example.NestedFXMLController">
</AnchorPane>

Controller classes: 控制器类:

public class MainController implements Initializable {

    @FXML
    private NestedFXMLController someIdController;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub

    }
}
public class NestedFXMLController implements Initializable {

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub

    }
}

Nice: The nested controller can be injected via FXML annotation. 不错:嵌套控制器可以通过FXML注释注入。 The field name must match the fx:id attribute string + "Controller"! 字段名称必须与fx:id属性字符串+“Controller”匹配!

This can definitely be achieved by creating a separate FXML file and add a Node to it with a known unique Id, then accessing that node via the id, the tricky part is how are you going to do it application wide? 这绝对可以通过创建一个单独的FXML文件并使用已知的唯一ID添加一个Node,然后通过id访问该节点来实现,棘手的部分是你将如何在应用程序范围内进行? probably creating the same function in a lot of your controllers but here is how you would get aa button from an FXML file. 可能在很多控制器中创建了相同的功能,但这里是你如何从FXML文件中获得一个按钮。

All buttons are performing the same action? 所有按钮都执行相同的操作?

Parent root = FXMLLoader.load(getClass().getResource("fileName.fxml"));

        ObservableList<Node> nodes = root.getChildrenUnmodifiable();
        String _id = "testButton";
        for (Node node : nodes) {
            if (node.getId().equals(_id)) {
                return node;
            }

        }
        return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM