Java Code Examples for javafx.fxml.FXMLLoader#setControllerFactory()

The following examples show how to use javafx.fxml.FXMLLoader#setControllerFactory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ActivityControllerTest.java    From PeerWasp with MIT License 6 votes vote down vote up
protected Parent getRootNode() {
	try {
		FXMLLoader loader = new FXMLLoader();
		loader.setControllerFactory(new Callback<Class<?>, Object>() {
			@Override
			public Object call(Class<?> param) {
				return controller;
			}
		});
		loader.setLocation(getClass().getResource(ViewNames.ACTIVITY_VIEW));
		return loader.load();
	} catch (IOException e) {
		e.printStackTrace();
		throw new RuntimeException(e);
	}
}
 
Example 2
Source File: FxmlViewLoader.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private View loadFromFxml(URL fxmlUrl) {
    checkNotNull(fxmlUrl, "FXML URL must not be null");
    try {
        FXMLLoader loader = new FXMLLoader(fxmlUrl, resourceBundle);
        loader.setControllerFactory(viewFactory);
        loader.load();
        Object controller = loader.getController();
        if (controller == null)
            throw new ViewfxException("Failed to load view from FXML file at [%s]. " +
                    "Does it declare an fx:controller attribute?", fxmlUrl);
        if (!(controller instanceof View))
            throw new ViewfxException("Controller of type [%s] loaded from FXML file at [%s] " +
                    "does not implement [%s] as expected.", controller.getClass(), fxmlUrl, View.class);
        return (View) controller;
    } catch (IOException ex) {
        throw new ViewfxException(ex, "Failed to load view from FXML file at [%s]", fxmlUrl);
    }
}
 
Example 3
Source File: DataSourceController.java    From mapper-generator-javafx with Apache License 2.0 6 votes vote down vote up
/**
 * 添加数据源的 stage
 *
 * @param primaryStage 主窗口
 * @throws IOException e
 */
void addDataSource(Stage primaryStage) throws IOException {
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("/fxml/datasource-setting.fxml"));
    fxmlLoader.setControllerFactory(applicationContext::getBean);

    Parent load = fxmlLoader.load();

    dateSourceStage = new Stage();
    dateSourceStage.setScene(new Scene(load));
    dateSourceStage.setResizable(false);
    dateSourceStage.getIcons().add(new Image("/image/[email protected]"));
    dateSourceStage.setTitle("设置数据源");
    dateSourceStage.initModality(Modality.WINDOW_MODAL);
    dateSourceStage.initOwner(primaryStage);
    dateSourceStage.show();
}
 
Example 4
Source File: AuxclasspathSetupController.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Displays the popup. */
public void show(Stage parentStage, List<File> currentItems, Consumer<List<File>> onApply) {

    FXMLLoader fxmlLoader = new FXMLLoader(DesignerUtil.getFxml("auxclasspath-setup-popup"));

    fxmlLoader.setControllerFactory(type -> {
        if (type == AuxclasspathSetupController.class) {
            return this;
        } else {
            throw new IllegalStateException("Wrong controller!");
        }
    });

    Stage stage = new Stage();
    try {
        stage.setScene(new Scene(fxmlLoader.load()));
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    fileListView.setItems(FXCollections.observableArrayList(currentItems));

    stage.setTitle("Auxilliary classpath setup");
    stage.initOwner(parentStage);
    stage.initModality(Modality.WINDOW_MODAL);

    setClassPathButton.setOnAction(e -> {
        stage.close();
        onApply.accept(fileListView.getItems());
    });

    cancelButton.setOnAction(e -> stage.close());

    stage.show();
}
 
Example 5
Source File: AbstractFxmlView.java    From spring-labs with Apache License 2.0 5 votes vote down vote up
private FXMLLoader loadSynchronously(URL resource, ResourceBundle bundle) throws IllegalStateException {

		FXMLLoader loader = new FXMLLoader(resource, bundle);
		loader.setControllerFactory(this::createControllerForType);

		try {
			loader.load();
		} catch (IOException ex) {
			throw new IllegalStateException("Cannot load " + getConventionalName(), ex);
		}

		return loader;
	}
 
Example 6
Source File: GuiceFxmlLoader.java    From PeerWasp with MIT License 5 votes vote down vote up
@Override
public FXMLLoader create(final String fxmlFile, Injector injector) throws IOException {
	FXMLLoader loader = new FXMLLoader();
	loader.setLocation(getClass().getResource(fxmlFile));
	loader.setControllerFactory(new Callback<Class<?>, Object>() {
		@Override
		public Object call(Class<?> type) {
			return injector.getInstance(type);
		}
	});
	return loader;
}
 
Example 7
Source File: EditorApp.java    From FXTutorials with MIT License 5 votes vote down vote up
@Override
public void start(Stage stage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("ui.fxml"));
    loader.setControllerFactory(t -> new EditorController(new EditorModel()));

    stage.setScene(new Scene(loader.load()));
    stage.show();
}
 
Example 8
Source File: DependencyResolveDialog.java    From SmartModInserter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void load() throws IOException {
    FXMLLoader loader = new FXMLLoader();
    loader.setControllerFactory(clazz -> this);
    loader.setLocation(getClass().getResource("/dependencydialog.fxml"));
    loader.load();
}
 
Example 9
Source File: Controller.java    From xdat_editor with MIT License 5 votes vote down vote up
private Node loadScriptTabContent() {
    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("scripting/main.fxml"));
        loader.setClassLoader(getClass().getClassLoader());
        loader.setControllerFactory(param -> new acmi.l2.clientmod.xdat.scripting.Controller(editor));
        return wrap(loader.load());
    } catch (IOException e) {
        log.log(Level.WARNING, "Couldn't load script console", e);
    }
    return null;
}
 
Example 10
Source File: LogEntryEditorStage.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * A stand-alone window containing components needed to create a logbook entry.
 * @param parent The {@link Node} from which the user - through context menu or application menu - requests a new
 *               logbook entry.
 * @param logEntryModel Pre-populated data for the log entry, e.g. date and (optionally) screen shot.
 * @param completionHandler If non-null, called when the submission to the logbook service has completed.
 */
public LogEntryEditorStage(Node parent, LogEntryModel logEntryModel, LogEntryCompletionHandler completionHandler)
{
    initModality(Modality.APPLICATION_MODAL);
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("LogEntryEditor.fxml"));
    fxmlLoader.setControllerFactory(clazz -> {
        try {
            if(clazz.isAssignableFrom(LogEntryEditorController.class)){
                LogEntryEditorController logEntryEditorController =
                        (LogEntryEditorController)clazz.getConstructor(Node.class, LogEntryModel.class, LogEntryCompletionHandler.class)
                        .newInstance(parent, logEntryModel, completionHandler);
                return logEntryEditorController;
            }
            else if(clazz.isAssignableFrom(FieldsViewController.class)){
                FieldsViewController fieldsViewController = (FieldsViewController)clazz.getConstructor(LogEntryModel.class)
                        .newInstance(logEntryModel);
                return fieldsViewController;
            }
            else if(clazz.isAssignableFrom(AttachmentsViewController.class)){
                AttachmentsViewController attachmentsViewController =
                        (AttachmentsViewController)clazz.getConstructor(Node.class, List.class, List.class, Boolean.class)
                                .newInstance(parent, logEntryModel.getImages(), logEntryModel.getFiles(), true);
                return attachmentsViewController;
            }
        } catch (Exception e) {
            Logger.getLogger(LogEntryEditorStage.class.getName()).log(Level.SEVERE, "Failed to contruct controller for log editor UI", e);
        }
        return null;
    });

    try {
        fxmlLoader.load();
    } catch (
            IOException exception) {
        Logger.getLogger(LogEntryEditorStage.class.getName()).log(Level.WARNING, "Unable to load fxml for log entry editor", exception);
    }

    Scene scene = new Scene(fxmlLoader.getRoot());
    setScene(scene);
}
 
Example 11
Source File: SpringFxmlLoader.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
public Object load(String url) {
    try {
        loader = new FXMLLoader();
        loader.setLocation(SpringFxmlLoader.class.getResource(url));
        loader.setControllerFactory(clazz -> ApplicationContextProvider.getApplicationContext().getBean(clazz));
        return loader.load();
    } catch (IOException ioException) {
        throw new RuntimeException(ioException);
    }
}
 
Example 12
Source File: MainController.java    From mapper-generator-javafx with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
@Override
public void initialize(URL location, ResourceBundle resources) {
    hostServices = beanFactory.getBean(HostServices.class);
    StageConstants.primaryStage = beanFactory.getBean(Stage.class);

    // 把菜单的长度和主布局控件绑定
    menuBar.prefWidthProperty().bind(borderPane.widthProperty());

    dataSourceTreeViewInit.treeViewInit(treeViewDataSource);

    // init mapperCheckBox
    mapperCheckBoxInit.checkBoxInit(mapperCheckBoxHBox1, mapperCheckBoxHBox2);

    // 从文件加载数据源至pane
    dataSourceTreeItemInit.initLoadData(treeItemDataSourceRoot);
    // 添加表搜索监听
    dataSourceTreeItemInit.addListenOnDataSourceBorderPane(treeViewDataSource);

    FXMLLoader fxmlLoader = new FXMLLoader();

    fxmlLoader.setLocation(getClass().getResource("/fxml/component/vbox-context-menu.fxml"));
    fxmlLoader.setControllerFactory(beanFactory::getBean);

    ListView<HBox> rightListViewInit = fxmlLoader.load();
    borderPane1.setCenter(rightListViewInit);
}
 
Example 13
Source File: MapperGenApplication.java    From mapper-generator-javafx with Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
    applicationContext = SpringApplication.run(MapperGenApplication.class);
    fxmlLoader = new FXMLLoader();
    fxmlLoader.setControllerFactory(applicationContext::getBean);
    HostServices hostServices = getHostServices();
    applicationContext.getBeanFactory().registerSingleton("hostServices", hostServices);
}
 
Example 14
Source File: StageBuilder.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public StageBuilder withFxml(URL fxmlUrl, @NonNull DesignerRoot root, Object... controllers) {
    FXMLLoader loader = new FXMLLoader(fxmlUrl);
    loader.setBuilderFactory(customBuilderFactory(root));
    loader.setControllerFactory(controllerFactoryKnowing(controllers));
    Parent parent;
    try {
        parent = loader.load();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    return withSceneRoot(parent);
}
 
Example 15
Source File: Designer.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void start(Stage stage, DesignerRoot owner) throws IOException {
    this.designerRoot = owner;

    stage.setTitle("PMD Rule Designer (v " + Designer.VERSION + ')');
    setIcons(stage);

    Logger.getLogger(Attribute.class.getName()).setLevel(Level.OFF);

    System.out.println(stage.getTitle() + " initializing... ");

    FXMLLoader loader = new FXMLLoader(DesignerUtil.getFxml("designer"));

    MainDesignerController mainController = new MainDesignerController(owner);

    loader.setBuilderFactory(DesignerUtil.customBuilderFactory(owner));

    loader.setControllerFactory(DesignerUtil.controllerFactoryKnowing(
        mainController,
        new MetricPaneController(owner),
        new ScopesPanelController(owner),
        new NodeDetailPaneController(owner),
        new RuleEditorsController(owner),
        new SourceEditorController(owner)
    ));

    stage.setOnCloseRequest(e -> {
        owner.getService(DesignerRoot.PERSISTENCE_MANAGER).persistSettings(mainController);
        Platform.exit();
        // VM sometimes fails to exit for no apparent reason
        // all our threads are killed so it's not our fault
        System.exit(0);
    });

    Parent root = loader.load();
    Scene scene = new Scene(root);

    stage.setScene(scene);

    stage.show();

    if (!owner.isDeveloperMode()) {
        // only close after initialization succeeded.
        // so that fatal errors thrown by stage.show are not hidden
        System.err.close();
    }


    long initTime = System.currentTimeMillis() - initStartTimeMillis;

    System.out.println("done in " + initTime + "ms.");
    if (!owner.isDeveloperMode()) {
        System.out.println("Run with --verbose parameter to enable error output.");
    }
}
 
Example 16
Source File: XdatEditor.java    From xdat_editor with MIT License 4 votes vote down vote up
@Override
public void start(Stage primaryStage) throws Exception {
    this.stage = primaryStage;

    FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml"), interfaceResources);
    loader.setClassLoader(getClass().getClassLoader());
    loader.setControllerFactory(param -> new Controller(XdatEditor.this));
    Parent root = loader.load();
    controller = loader.getController();

    primaryStage.setTitle("XDAT Editor");
    primaryStage.setScene(new Scene(root));
    primaryStage.setWidth(Double.parseDouble(windowPrefs().get("width", String.valueOf(primaryStage.getWidth()))));
    primaryStage.setHeight(Double.parseDouble(windowPrefs().get("height", String.valueOf(primaryStage.getHeight()))));
    if (windowPrefs().getBoolean("maximized", primaryStage.isMaximized())) {
        primaryStage.setMaximized(true);
    } else {
        Rectangle2D bounds = new Rectangle2D(
                Double.parseDouble(windowPrefs().get("x", String.valueOf(primaryStage.getX()))),
                Double.parseDouble(windowPrefs().get("y", String.valueOf(primaryStage.getY()))),
                primaryStage.getWidth(),
                primaryStage.getHeight());
        if (Screen.getScreens()
                .stream()
                .map(Screen::getVisualBounds)
                .anyMatch(r -> r.intersects(bounds))) {
            primaryStage.setX(bounds.getMinX());
            primaryStage.setY(bounds.getMinY());
        }
    }
    primaryStage.show();

    Platform.runLater(() -> {
        InvalidationListener listener = observable -> {
            if (primaryStage.isMaximized()) {
                windowPrefs().putBoolean("maximized", true);
            } else {
                windowPrefs().putBoolean("maximized", false);
                windowPrefs().put("x", String.valueOf(Math.round(primaryStage.getX())));
                windowPrefs().put("y", String.valueOf(Math.round(primaryStage.getY())));
                windowPrefs().put("width", String.valueOf(Math.round(primaryStage.getWidth())));
                windowPrefs().put("height", String.valueOf(Math.round(primaryStage.getHeight())));
            }
        };
        primaryStage.xProperty().addListener(listener);
        primaryStage.yProperty().addListener(listener);
        primaryStage.widthProperty().addListener(listener);
        primaryStage.heightProperty().addListener(listener);
    });
    Platform.runLater(this::postShow);
}
 
Example 17
Source File: FXMLLoaderProvider.java    From ariADDna with Apache License 2.0 4 votes vote down vote up
public FXMLLoader get(String path) {
    FXMLLoader loader = new FXMLLoader(getClass().getResource(path));
    loader.setControllerFactory(param -> ctx.getBean(param));
    return loader;
}