Classpath resolution with hierarchical custom JavaFx components in Scenebuilder

ぐ巨炮叔叔 提交于 2019-12-03 04:04:52

Someone named David did answer your question on the forum. For legacy purpose I post it here.

There is a problem with the classloader in Scene Builder for custom components. When you load a FXML file in SceneBuilder: it uses a FXMLLoader with its own classloader. In order to load custom components which use their own FXMLLoader to load other custom components, it is necessary to make all FXMLLoader use the same classloader. As David said on the forum, you can achieve that by adding this code in your custom component.

public class CustomC extends VBox {
    public CustomC() {
        init();
    }

    private void init() {
        FXMLLoader loader = new FXMLLoader();
        loader.setRoot(this);
        loader.setLocation(this.getClass().getResource("CustomC.fxml"));

        // Make sure to load "CustomC.fxml" with the same classloader that
        // was used to load CustomC class. 
        loader.setClassLoader(this.getClass().getClassLoader());

        try {
           final Node root = (Node)loader.load();
           assert root == this;
        } catch (IOException ex) {
           throw new IllegalStateException(ex);
        }
    }
}

If you want to externalize this code in a class, it is important to put this class in the same jar as your custom components: you cannot put it in a external jar (at least for now).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!