001/* 002 * Copyright 2019-2021 M. Sean Gilligan. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package app.supernaut.fx.micronaut.fxml; 017 018import app.supernaut.fx.fxml.FxmlLoaderFactory; 019import io.micronaut.context.BeanContext; 020import javafx.fxml.FXMLLoader; 021 022import java.net.URL; 023 024/** 025 * Factory for providing FXMLLoaders that do full DI. This 026 * singleton is added to the Micronaut BeanContext with BeanContext#registerSingleton. 027 */ 028public class MicronautFxmlLoaderFactory implements FxmlLoaderFactory { 029 BeanContext context; 030 031 /** 032 * Constructor that gets BeanContext of the SupernautFX application injected. 033 * 034 * @param context The BeanContext of the SupernautFX application 035 */ 036 public MicronautFxmlLoaderFactory(BeanContext context) { 037 this.context = context; 038 } 039 040 /** 041 * Get the FXML controller from the BeanContext 042 * 043 * @param clazz The controller class we are looking for 044 * @param <T> The class type of the controller 045 * @return A controller instance 046 */ 047 public <T> T getControllerFactory(Class<T> clazz) { 048 return context.getBean(clazz); 049 } 050 051 /** 052 * Get an FXMLLoader without setting a location 053 * 054 * @return An FXMLLoader 055 */ 056 public FXMLLoader get() { 057 return get(null); 058 } 059 060 /** 061 * Get an FXMLLoader for the given location 062 * 063 * @param location The location of the FXML resource 064 * @return An FXMLLoader 065 */ 066 public FXMLLoader get(URL location) { 067 FXMLLoader loader = new FXMLLoader(location); 068 loader.setControllerFactory(this::getControllerFactory); 069 return loader; 070 } 071 072}