Example usage for javafx.fxml FXMLLoader FXMLLoader

List of usage examples for javafx.fxml FXMLLoader FXMLLoader

Introduction

In this page you can find the example usage for javafx.fxml FXMLLoader FXMLLoader.

Prototype

public FXMLLoader(URL location, ResourceBundle resources) 

Source Link

Document

Creates a new FXMLLoader instance.

Usage

From source file:caillou.company.clonemanager.gui.spring.SpringFxmlLoader.java

public static LoadingMojo load(String url, final String controllerClassName) {

    lastLoadedURL = url;//  w  w  w .  j  a v  a  2  s. c  o m
    FXMLLoader loader = new FXMLLoader(MainApp.class.getResource(url), resourceBundle);
    loader.setControllerFactory(new Callback<Class<?>, Object>() {
        @Override
        public Object call(Class<?> clazz) {
            if (controllerClassName != null) {
                try {
                    return applicationContext.getBean(Class.forName(controllerClassName));
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(SpringFxmlLoader.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            return applicationContext.getBean(clazz);
        }
    });

    try {
        Parent parent = loader.load();
        LoadingMojo loadingMojo = new LoadingMojo();
        loadingMojo.setController(loader.getController());
        loadingMojo.setParent(parent);
        return loadingMojo;
    } catch (IOException ex) {
        Logger.getLogger(SpringFxmlLoader.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception exMain) {
        System.out.println("Error");
    }
    return null;
}

From source file:intelligent.wiki.editor.spring.SpringFXMLLoader.java

/**
 * Loads an object from FXML document using Spring and {@link FXMLLoader}.
 *
 * @param url path to FXML document/*from   ww  w .j  a  v a  2  s  .  c  o  m*/
 * @param <T> type of loaded object
 * @return loaded object
 * @throws IOException if an I/O error occurs
 */
public <T> T load(URL url) throws IOException {
    loader = new FXMLLoader(url, i18n);
    loader.setControllerFactory(applicationContext::getBean);
    return loader.load();
}

From source file:com.ucu.seguridad.views.AbstractFxmlView.java

FXMLLoader loadSynchronously(URL resource, ResourceBundle bundle) throws IllegalStateException {

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

    try {//from  ww  w .ja  v a  2  s.c om
        loader.load();
    } catch (IOException ex) {
        throw new IllegalStateException("Cannot load " + getConventionalName(), ex);
    }

    return loader;
}

From source file:ubicrypt.ui.StackNavigator.java

public <R> Parent loadFrom(final Optional<R> data) {
    log.debug("fxml:{}", levels.peek());
    final FXMLLoader loader = new FXMLLoader(
            StackNavigator.class.getResource(format("/fxml/%s.fxml", levels.peek())), bundle);
    loader.setControllerFactory(controllerFactory);
    try {//from  w w  w .  j a  v  a 2 s  .  co m
        Parent parent;
        if (root != null) {
            root.getChildren().setAll((Node) loader.load());
            parent = (Parent) root.getChildren().get(0);
        } else {
            parent = loader.load();
        }
        Object controller = loader.getController();
        stream(getAllFields(controller.getClass())).filter(field -> field.getType() == StackNavigator.class)
                .forEach(field -> {
                    try {
                        writeField(field, controller, this, true);
                    } catch (IllegalAccessException e) {
                        log.error("error setting field:{} in:{}", field, controller);
                        Throwables.propagate(e);
                    }
                    log.debug("{} inject stack navigator", controller.getClass().getSimpleName());
                });
        if (Consumer.class.isAssignableFrom(controller.getClass())) {
            data.ifPresent(((Consumer<R>) controller)::accept);
        }
        return parent;
    } catch (final IOException e) {
        Throwables.propagate(e);
    }
    return null;
}

From source file:org.cryptomator.ui.MainApplication.java

@Override
public void start(final Stage primaryStage) throws IOException {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    Platform.runLater(() -> {/*  w w w .j a va 2  s  .  co  m*/
        /*
         * This fixes a bug on OSX where the magic file open handler leads
         * to no context class loader being set in the AppKit (event) thread
         * if the application is not started opening a file.
         */
        if (Thread.currentThread().getContextClassLoader() == null) {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
    });

    Runtime.getRuntime().addShutdownHook(MainApplication.CLEAN_SHUTDOWN_PERFORMER);

    executorService = Executors.newCachedThreadPool();
    addShutdownTask(() -> {
        executorService.shutdown();
    });

    WebDavServer.getInstance().start();
    chooseNativeStylesheet();
    final ResourceBundle rb = ResourceBundle.getBundle("localization");
    final FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"), rb);
    final Parent root = loader.load();
    final MainController ctrl = loader.getController();
    ctrl.setStage(primaryStage);
    final Scene scene = new Scene(root);
    primaryStage.setTitle(rb.getString("app.name"));
    primaryStage.setScene(scene);
    primaryStage.sizeToScene();
    primaryStage.setResizable(false);
    primaryStage.show();
    ActiveWindowStyleSupport.startObservingFocus(primaryStage);
    TrayIconUtil.init(primaryStage, rb, () -> {
        quit();
    });

    for (String arg : getParameters().getUnnamed()) {
        handleCommandLineArg(ctrl, arg);
    }

    if (org.controlsfx.tools.Platform.getCurrent().equals(org.controlsfx.tools.Platform.OSX)) {
        Main.OPEN_FILE_HANDLER.complete(file -> handleCommandLineArg(ctrl, file.getAbsolutePath()));
    }

    LocalInstance cryptomatorGuiInstance = SingleInstanceManager.startLocalInstance(APPLICATION_KEY,
            executorService);
    addShutdownTask(() -> {
        cryptomatorGuiInstance.close();
    });

    cryptomatorGuiInstance.registerListener(arg -> handleCommandLineArg(ctrl, arg));
}

From source file:viewfx.view.support.fxml.FxmlViewLoader.java

public View loadFromFxml(URL fxmlUrl) {
    checkNotNull(fxmlUrl, "FXML URL must not be null");
    try {//from w ww.  j a v a2  s.  c o m
        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);
    }
}

From source file:net.rptools.tokentool.client.TokenTool.java

@Override
public void start(Stage primaryStage) throws IOException {
    stage = primaryStage;/*  w w w. java 2s . c o  m*/
    setUserAgentStylesheet(STYLESHEET_MODENA); // Setting the style back to the new Modena
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(AppConstants.TOKEN_TOOL_FXML),
            ResourceBundle.getBundle(AppConstants.TOKEN_TOOL_BUNDLE));
    root = fxmlLoader.load();
    tokentool_Controller = (TokenTool_Controller) fxmlLoader.getController();

    Scene scene = new Scene(root);
    primaryStage.setTitle(I18N.getString("TokenTool.stage.title"));
    primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(AppConstants.TOKEN_TOOL_ICON)));
    primaryStage.setScene(scene);

    primaryStage.widthProperty().addListener((obs, oldVal, newVal) -> {
        if (Double.isNaN(oldVal.doubleValue()))
            return;

        deltaX += newVal.doubleValue() - oldVal.doubleValue();

        // Only adjust on even width adjustments
        if (deltaX > 1 || deltaX < -1) {
            if (deltaX % 2 == 0) {
                tokentool_Controller.updatePortraitLocation(deltaX, 0);
                deltaX = 0;
            } else {
                tokentool_Controller.updatePortraitLocation(deltaX - 1, 0);
                deltaX = 1;
            }
        }
    });

    primaryStage.heightProperty().addListener((obs, oldVal, newVal) -> {
        if (Double.isNaN(oldVal.doubleValue()))
            return;

        deltaY += newVal.doubleValue() - oldVal.doubleValue();

        // Only adjust on even width adjustments
        if (deltaY > 1 || deltaY < -1) {
            if (deltaY % 2 == 0) {
                tokentool_Controller.updatePortraitLocation(0, deltaY);
                deltaY = 0;
            } else {
                tokentool_Controller.updatePortraitLocation(0, deltaY - 1);
                deltaY = 1;
            }
        }
    });

    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
        @Override
        public void handle(WindowEvent event) {
            tokentool_Controller.exitApplication();
        }
    });

    // Load all the overlays into the treeview
    tokentool_Controller.updateOverlayTreeview(overlayTreeItems);

    // Restore saved settings
    AppPreferences.restorePreferences(tokentool_Controller);

    // Add recent list to treeview
    tokentool_Controller.updateOverlayTreeViewRecentFolder(true);

    // Set the Overlay Options accordion to be default open view
    tokentool_Controller.expandOverlayOptionsPane(true);

    primaryStage.show();

    // Finally, update token preview image after everything is done loading
    Platform.runLater(() -> tokentool_Controller.updateTokenPreviewImageView());
}

From source file:acmi.l2.clientmod.xdat.XdatEditor.java

@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();//from   w w w  . ja  v  a 2 s .c  o  m
    controller = loader.getController();

    primaryStage.setTitle("XDAT Editor");
    primaryStage.setScene(new Scene(root));
    primaryStage.show();

    postShow();
}

From source file:com.github.tddts.jet.view.fx.spring.DialogProvider.java

private FXMLLoader loadDialogView(FxDialog dialogAnnotation) {

    String filePath = dialogAnnotation.value();

    if (filePath.isEmpty()) {
        throw new DialogException("@FxDialog should contain path to FXML file!");
    }//  w  w w.ja  va2 s. co m

    FXMLLoader loader = new FXMLLoader(Util.getClasspathResourceURL(filePath),
            resourceBundleProvider.getResourceBundle());

    try {
        loader.load();
    } catch (IOException e) {
        throw new DialogException(e.getMessage(), e);
    }

    return loader;
}

From source file:com.QuarkLabs.BTCeClientJavaFX.MainController.java

@FXML
void initialize() {
    assert clearLogButton != null : "fx:id=\"clearLogButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert fundsTable != null : "fx:id=\"fundsTable\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert logField != null : "fx:id=\"logField\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert buyButton != null : "fx:id=\"buyButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert sellButton != null : "fx:id=\"sellButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert showActiveOrdersButton != null : "fx:id=\"showActiveOrdersButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableLastColumn != null : "fx:id=\"tickerTableLastColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTablePairColumn != null : "fx:id=\"tickerTablePairColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTable != null : "fx:id=\"tickersTable\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableBuyColumn != null : "fx:id=\"tickersTableBuyColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableFeeColumn != null : "fx:id=\"tickersTableFeeColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableSellColumn != null : "fx:id=\"tickersTableSellColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradeAmountValue != null : "fx:id=\"tradeAmountValue\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradePriceCurrencyType != null : "fx:id=\"tradeCurrencyPriceValue\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradeCurrencyType != null : "fx:id=\"tradeCurrencyType\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradePriceValue != null : "fx:id=\"tradePriceValue\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert updateFundsButton != null : "fx:id=\"updateFundsButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert fundsTableCurrencyColumn != null : "fx:id=\"fundsTableCurrencyColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert fundsTableValueColumn != null : "fx:id=\"fundsTableValueColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersTable != null : "fx:id=\"fundsTableValueColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersAmountColumn != null : "fx:id=\"activeOrdersAmountColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersPairColumn != null : "fx:id=\"activeOrdersPairColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersRateColumn != null : "fx:id=\"activeOrdersRateColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersTimeColumn != null : "fx:id=\"activeOrdersTimeColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersTypeColumn != null : "fx:id=\"activeOrdersTypeColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersCancelColumn != null : "fx:id=\"activeOrdersCancelColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";

    //Holder for all main API methods of exchange
    app = new App();

    //Loading configs
    loadExchangeConfig();//from  w ww.ja v  a2  s . c o  m

    //Populate choiceboxes at the trading section
    tradeCurrencyType.setItems(FXCollections.observableArrayList(currencies));
    tradeCurrencyType.setValue(currencies.get(0));
    tradePriceCurrencyType.setItems(FXCollections.observableArrayList(currencies));
    tradePriceCurrencyType.setValue(currencies.get(0));

    //Active Orders table
    activeOrdersAmountColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, Double>("amount"));
    activeOrdersPairColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, String>("pair"));
    activeOrdersRateColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, Double>("rate"));
    activeOrdersTimeColumn.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<ActiveOrder, String>, ObservableValue<String>>() {
                @Override
                public ObservableValue<String> call(
                        TableColumn.CellDataFeatures<ActiveOrder, String> activeOrderStringCellDataFeatures) {
                    ActiveOrder activeOrder = activeOrderStringCellDataFeatures.getValue();
                    DateFormat dateFormat = DateFormat.getDateTimeInstance();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(activeOrder.getTimestamp() * 1000);
                    return new SimpleStringProperty(dateFormat.format(calendar.getTime()));
                }
            });
    activeOrdersTypeColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, String>("type"));
    activeOrdersTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    activeOrdersCancelColumn
            .setCellFactory(new Callback<TableColumn<ActiveOrder, Boolean>, TableCell<ActiveOrder, Boolean>>() {
                @Override
                public TableCell<ActiveOrder, Boolean> call(
                        TableColumn<ActiveOrder, Boolean> activeOrderBooleanTableColumn) {
                    return new ButtonCell<>(activeOrdersTable);
                }
            });
    activeOrdersCancelColumn.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<ActiveOrder, Boolean>, ObservableValue<Boolean>>() {
                @Override
                public ObservableValue<Boolean> call(
                        TableColumn.CellDataFeatures<ActiveOrder, Boolean> activeOrderBooleanCellDataFeatures) {
                    return new SimpleBooleanProperty(true);
                }
            });

    //Tickers Table
    MenuItem showOrdersBook = new MenuItem("Show Orders Book");
    MenuItem showPublicTrades = new MenuItem("Show Public Trades");

    ContextMenu contextMenu = new ContextMenu(showOrdersBook, showPublicTrades);

    tickersTable.setItems(tickers);
    tickersTable.setContextMenu(contextMenu);
    tickersTableBuyColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("buy"));
    tickersTableFeeColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("fee"));
    tickersTableSellColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("sell"));
    tickersTableLastColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("last"));
    tickersTablePairColumn.setCellValueFactory(new PropertyValueFactory<Ticker, String>("pair"));
    tickersTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    tickersTable.setRowFactory(new Callback<TableView<Ticker>, TableRow<Ticker>>() {
        @Override
        public TableRow<Ticker> call(TableView<Ticker> tickerTableView) {
            return new TableRow<Ticker>() {
                @Override
                protected void updateItem(Ticker ticker, boolean b) {
                    super.updateItem(ticker, b);
                    if (!b) {
                        if (tickersData.containsKey(ticker.getPair())) {
                            if (ticker.getLast() < tickersData.get(ticker.getPair()).getLast()) {
                                setStyle("-fx-control-inner-background: rgba(186, 0, 0, 0.5);");
                            } else if (ticker.getLast() == tickersData.get(ticker.getPair()).getLast()) {
                                setStyle("-fx-control-inner-background: rgba(215, 193, 44, 0.5);");
                            } else {
                                setStyle("-fx-control-inner-background: rgba(0, 147, 0, 0.5);");
                            }
                        }
                    }
                }
            };
        }
    });

    //Menu item to show Orders Book
    showOrdersBook.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            Ticker selectedTicker = tickersTable.getSelectionModel().getSelectedItem();
            Parent root;
            try {
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(PATH_TO_ORDERS_BOOK_LAYOUT),
                        resources);
                root = (Parent) fxmlLoader.load();
                OrdersBookController ordersBookController = fxmlLoader.getController();
                ordersBookController.injectPair(selectedTicker.getPair());
                Stage stage = new Stage();
                stage.setTitle("Orders Book for " + selectedTicker.getPair().replace("_", "/").toUpperCase());
                stage.setScene(new Scene(root));
                stage.setResizable(false);
                stage.show();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    //Menu item to show Public Trades
    showPublicTrades.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            Ticker selectedTicker = tickersTable.getSelectionModel().getSelectedItem();
            Parent root;
            try {
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(PATH_TO_TRADES_LAYOUT),
                        resources);
                root = (Parent) fxmlLoader.load();
                PublicTradesController publicTradesController = fxmlLoader.getController();
                publicTradesController.injectPair(selectedTicker.getPair());
                Stage stage = new Stage();
                stage.setTitle("Public Trades for " + selectedTicker.getPair().replace("_", "/").toUpperCase());
                stage.setScene(new Scene(root));
                stage.setResizable(false);
                stage.show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    //Funds Table
    fundsTableCurrencyColumn.setCellValueFactory(new PropertyValueFactory<Fund, String>("currency"));
    fundsTableValueColumn.setCellValueFactory(new PropertyValueFactory<Fund, Double>("value"));
    fundsTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    fundsTable.setItems(fundsData);

    //Task to load tickers data from server
    final javafx.concurrent.Service loadTickersService = new javafx.concurrent.Service() {
        @Override
        protected Task createTask() {
            Task<JSONObject> loadTickers = new Task<JSONObject>() {
                @Override
                protected JSONObject call() throws Exception {
                    String[] pairsArray = new String[pairs.size()];
                    pairsArray = pairs.toArray(pairsArray);
                    return App.getPairInfo(pairsArray);
                }
            };

            loadTickers.setOnFailed(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent workerStateEvent) {
                    logField.appendText(workerStateEvent.getSource().getException().getMessage() + "\r\n");
                }
            });

            loadTickers.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent workerStateEvent) {
                    JSONObject jsonObject = (JSONObject) workerStateEvent.getSource().getValue();

                    //ugly hack to store old values
                    //dump old values to tickersData
                    //TODO think about better solution
                    if (tickers.size() != 0) {
                        for (Ticker x : tickers) {
                            tickersData.put(x.getPair(), x);
                        }
                    }
                    tickers.clear();
                    for (Iterator iterator = jsonObject.keys(); iterator.hasNext();) {
                        String key = (String) iterator.next();
                        JSONObject data = jsonObject.getJSONObject(key);
                        Ticker ticker = new Ticker();
                        ticker.setPair(key);
                        ticker.setUpdated(data.optLong("updated"));
                        ticker.setAvg(data.optDouble("avg"));
                        ticker.setBuy(data.optDouble("buy"));
                        ticker.setSell(data.optDouble("sell"));
                        ticker.setHigh(data.optDouble("high"));
                        ticker.setLast(data.optDouble("last"));
                        ticker.setLow(data.optDouble("low"));
                        ticker.setVol(data.optDouble("vol"));
                        ticker.setVolCur(data.optDouble("vol_cur"));
                        tickers.add(ticker);
                    }

                }
            });
            return loadTickers;
        }
    };

    //Update tickers every 15 seconds
    //TODO better solution is required
    Timeline timeline = new Timeline(new KeyFrame(Duration.ZERO, new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            loadTickersService.restart();
        }
    }), new KeyFrame(Duration.seconds(15)));
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.playFromStart();

}