Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Give each FXML document its own controller by setting a different fx:controller class on its root element. Load each document with its own FXMLLoader, then retrieve that view’s controller from the same loader with getController(). For separate screens, load and display the screen you need; use fx:include when you want multiple FXML components in one screen.

How the one-FXML, one-controller pattern works

A normal FXML document can name one root controller, but an application can have many FXML documents and many controllers. The association belongs to each document, not to the whole application. For example, login.fxml can use LoginController, while dashboard.fxml uses DashboardController. An FXML file can also omit fx:controller if you supply its controller in Java or do not need a controller.

When an FXML file declares fx:controller, FXMLLoader constructs that controller during loading. Fields marked with @FXML are injected as the document is processed; the controller’s initialize() callback runs after injection. See Oracle’s FXML introduction for the controller and loading model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Organize the FXML files and controllers

Keep the resource files on the classpath and give each view a controller that owns its controls and view-specific behavior. A small project might look like this:

#1 Best Overall
Sale
Nulaxy Ergonomic Adjustable Laptop Stand for Desk, Dual Foldable Computer Riser with Advanced Heat-Vent, Heavy-Duty Portable Notebook Holder for Posture Correction, Compatible with Mac 10-16" Laptops
  • Ergonomic Posture Correction: Designed to elevate your laptop to the perfect eye level, this adjustable laptop stand significantly reduces neck, shoulder, and spinal fatigue. Transform your desk into a healthier workstation, ideal for long hours of typing, Zoom meetings, or gaming.
  • Unshakable Dual-Rod Stability: Unlike single-hinge models, our stand features a highly engineered dual-support rod mechanism. It perfectly distributes weight to ensure a 100% wobble-free typing experience, safely supporting heavy-duty devices up to 22 lbs (10kg).
  • Advanced Thermal Cooling Panel: Maximize your device's performance. The unique geometric heat-vent design on the upper panel provides superior airflow compared to standard solid stands. This continuous heat dissipation prevents your laptop from thermal throttling and hardware damage during intensive tasks.
  • Universal 10-16” Compatibility: A versatile computer riser that seamlessly fits all 10 to 16-inch laptops. Broadly compatible with MacBook Pro/Air, Dell XPS, HP, Lenovo, ASUS, Chromebook, and large gaming laptops. The anti-slip silicone pads firmly grip your device and protect it from scratches.
  • Foldable, Portable & Ready to Go: Maximize your productivity anywhere. The dual-foldable design allows the stand to collapse completely flat in seconds. Easily slip it into your backpack or briefcase, making it the ultimate portable office accessory for business trips, cafes, or hybrid work setups.
src/main/resources/com/example/app/
    login.fxml
    dashboard.fxml
    settings.fxml

src/main/java/com/example/app/
    LoginController.java
    DashboardController.java
    SettingsController.java
    Main.java

For resources in that package, use a consistent package declaration in the Java classes and a class-relative resource lookup such as Main.class.getResource("login.fxml").

Assign a different controller in each FXML file

Put the fully qualified controller class name on each document’s root element. The handler name after # must correspond to a compatible method in that file’s controller.

<!-- login.fxml -->
<VBox xmlns="http://javafx.com/javafx"
      xmlns:fx="http://javafx.com/fxml"
      fx:controller="com.example.app.LoginController">
    <TextField fx:id="usernameField" />
    <Button text="Log in" onAction="#handleLogin" />
</VBox>
<!-- dashboard.fxml -->
<BorderPane xmlns="http://javafx.com/javafx"
            xmlns:fx="http://javafx.com/fxml"
            fx:controller="com.example.app.DashboardController">
    <center>
        <Label fx:id="welcomeLabel" text="Welcome" />
    </center>
</BorderPane>

Use @FXML for private injected fields and handlers. The controller should focus on its own view, while application-wide state and business logic belong in shared models or services.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
package com.example.app;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;

public final class LoginController {
    @FXML private TextField usernameField;

    @FXML
    private void handleLogin() {
        String username = usernameField.getText();
        // Validate or authenticate, then signal success.
    }
}

Load a view and get its controller

Use a new loader for the FXML document you are loading. Call load() first, then ask that same loader for its controller. The controller returned this way is the instance whose fields were injected.

Rank #2
Sale
BESIGN LS03 Aluminum Laptop Stand, Ergonomic Detachable Computer Stand, Notebook Riser, Laptop Mount Compatible with Air, Pro, Dell, HP, Lenovo More 10-15.6" Laptops, Silver
  • Broad Compatibility: Besign LS03 Laptop Mount is compatible with all laptops from 10''-15.6'', such as Air 13, Pro 13 / 15 / 2018 / 2017 / 2016, Lenovo ThinkPad, Dell, HP, ASUS, Chromebook, and other notebooks.
  • Ergonomic Design: This LS03 Laptop Stand could elevate your laptop by 6’’ to a perfect viewing level, help you improve your posture and reduce neck and shoulder pain. This laptop stand is super easy to detach and assemble.
  • Stable And Protective: This laptop stand is made of premium Aluminum alloy, it is sturdy, support up to 8.8 lbs(4kg), no worry any wobble at all; the rubber on the holder hands sticks tightly, ensure your laptop stable on the stand and prevent any scratches.
  • Keep Laptop Cool: the open aluminum design provides good ventilation and airflow to prevent your laptop from overheating. It folds flat if you need to store it, create extra space on your desk and keep your desk clean and organized.
  • Easy to Use: thanks to the detachable design, you could assemble it very easily it 3 steps.
FXMLLoader loader = new FXMLLoader(
        Main.class.getResource("dashboard.fxml"));

Parent root = loader.load();
DashboardController controller = loader.getController();

The resource must exist in the packaged application. For a resource path independent of the calling class’s package, use an absolute classpath path, for example Main.class.getResource("/com/example/app/dashboard.fxml"). The FXMLLoader API documents getController(), controller factories and loading.

Switch between separate screens

For a simple application, replace the primary stage’s scene when navigation occurs. The login controller can expose a callback so it does not need to know how the application changes screens.

public final class LoginController {
    private Runnable onLoginSuccess;

    public void setOnLoginSuccess(Runnable callback) {
        this.onLoginSuccess = callback;
    }

    @FXML
    private void handleLogin() {
        // Authenticate first.
        if (onLoginSuccess != null) {
            onLoginSuccess.run();
        }
    }
}
public final class Main extends Application {
    private Stage stage;

    @Override
    public void start(Stage stage) throws IOException {
        this.stage = stage;
        showLogin();
        stage.setTitle("Example Application");
        stage.show();
    }

    private void showLogin() throws IOException {
        FXMLLoader loader = new FXMLLoader(
                getClass().getResource("login.fxml"));
        Parent root = loader.load();

        LoginController controller = loader.getController();
        controller.setOnLoginSuccess(() -> {
            try {
                showDashboard();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        });

        stage.setScene(new Scene(root));
    }

    private void showDashboard() throws IOException {
        FXMLLoader loader = new FXMLLoader(
                getClass().getResource("dashboard.fxml"));
        Parent root = loader.load();
        stage.setScene(new Scene(root));
    }
}

Replacing the scene is one navigation choice. In a larger application, a navigation or screen-management class can own these loading decisions. To update only part of a screen, replace the relevant content pane instead; use a separate Stage or Dialog for an independent window.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Share state without coupling unrelated controllers

A callback is suitable for a small action such as “login succeeded.” If several views need the same application state, pass them the same model or service instance rather than relying on controller globals or manually creating duplicate controllers.

Rank #3
Sale
LOXP Adjustable Laptop Stand, Computer Stand with 360 Rotating Base
  • ✔️[Foldabe & Protable] - Foldable laptop stand for desk & Protable computer stand, It combines the advantages of market brackets, convenient travel laptop stand. Easy to use. Suitable for working at home, office and outdoor, improve comfort.
  • ✔️[360°Rotation] - The computer stand with 360° rotating base, 360° rotation connected with the base is more flexible, the computer stand allows you to rotate the laptop to any angle.
  • ✔️[Stable & Durable] - The Computer stand is made of one-piece fiber metal material, which is more durable and stable than ordinary aluminum alloy computer stands. The upgraded rotating base makes the stand performance more stable, and the non-slip silicone protects the laptop from sliding.Only supports laptops up to 16 inches.
  • ✔️[Ergonmic Desing] - You can freely adjust the height and angle of the laptop stand to keep it at eye level, which helps to reduce the pressure on your body while working. Whether sitting or standing, there is a comfortable angle.
  • ✔️[Wide Compatibility] - Our laptop stand is compatible with all laptops from 10-16 inches, such as MacBook Air/Pro, Google PixelBook, Dell XPS, HP, ASUS, Lenovo ThinkPad, Acer, Chromebook and Microsoft Surface, etc. It is an ideal companion for computer workers.
public final class AppSession {
    private final StringProperty username = new SimpleStringProperty();

    public StringProperty usernameProperty() {
        return username;
    }

    public String getUsername() {
        return username.get();
    }

    public void setUsername(String value) {
        username.set(value);
    }
}

For example, after loading a dashboard, application code can call a setter on the retrieved controller to provide the shared session and then ask it to refresh. A parent controller coordinating included child views is another reasonable place for direct references. Keep unrelated controllers communicating through a model, service, event or navigation abstraction.

Compose FXML components with fx:include

Use fx:include when one screen should contain several reusable FXML components, such as a menu and a content panel. This is composition, not navigation between independently displayed screens.

<!-- main.fxml -->
<BorderPane xmlns="http://javafx.com/javafx"
            xmlns:fx="http://javafx.com/fxml"
            fx:controller="com.example.app.MainController">
    <top>
        <fx:include fx:id="menu" source="menu.fxml" />
    </top>
    <center>
        <fx:include fx:id="content" source="content.fxml" />
    </center>
</BorderPane>

If the included files declare their own controllers, the parent can inject those controllers by appending Controller to the include’s fx:id:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
public final class MainController {
    @FXML private MenuController menuController;
    @FXML private ContentController contentController;

    @FXML
    private void initialize() {
        // Included controllers are available here.
    }
}

The included root can also be injected using the include ID itself if the field type matches that root. Oracle’s FXML documentation explains nested controllers and includes.

Rank #4
Gogoonike Adjustable Laptop Stand for Desk, Metal Laptop Riser Holder
  • 【Adjustable & Ergonomic】:This laptop stand can be adjusted to a comfortable height and angle according to your actual needs, letting you fix posture and reduce your neck fatigue, back pain and eye strain. Very comfortable for working in home, office and outdoor.
  • 【Sturdy & Protective】 :Made of sturdy metal, it can support up to 17.6 lbs (8kg) weight on top; With 2 rubber mats on the hook and anti-skid silicone pads on top & bottom, it can secure your laptop in place and maximum protect your device from scratches and sliding. Moreover, smooth edges will never hurt your hands.
  • 【Heat Dissipation】 :The top of the laptop stand is designed with multiple ventilation holes. The open design offers greater ventilation and more airflow to cool your laptop during operation other than it just lays flat on the table.
  • 【Portable & Foldable】:The foldable design allows you to easily slip it in your backpack. Ideal for people who travel for business a lot.
  • 【Broad Compatibility】:Our desktop book stand is compatible with all laptops from 10-15.6 inches, such as MacBook Air/ Pro, Google Pixelbook, Dell XPS, HP, ASUS, Lenovo ThinkPad, Acer, Chromebook and Microsoft Surface, etc.Be your ideal companion in Home, Office & Outdoor.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Supply controllers with dependencies

There are two built-in approaches when a controller needs constructor arguments. Choose one controller-creation strategy for a given FXML file.

Provide a preconstructed controller with setController()

Create the controller before loading and assign it to the loader. Because Java supplies the controller, remove fx:controller from that FXML file. Call setController() before load().

AppSession session = new AppSession();
LoginController controller = new LoginController(session);

FXMLLoader loader = new FXMLLoader(
        getClass().getResource("login.fxml"));
loader.setController(controller);
Parent root = loader.load();

This supplies an already constructed instance; the loader still performs FXML injection during loading. Do not also declare fx:controller, or the loader may report that the controller value was already specified.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use setControllerFactory() for application-managed creation

A controller factory lets the loader request controller instances from application code. Install it before loading. This is useful when several controllers share services or an existing dependency-injection container is already in use.

Best Value
Tonmom Adjustable Laptop Stand for Desk, Metal Foldable Laptop Riser
  • ✅【Adjustable & Ergonomic】:This laptop stand can be adjusted to a comfortable height and angle according to your actual needs, letting you fix posture and reduce your neck fatigue, back pain and eye strain. Very comfortable for working in home, office and outdoor.
  • ✅【Sturdy & Protective】 :Made of sturdy metal, it can support up to 17.6 lbs (8kg) weight on top; With 2 rubber mats on the hook and anti-skid silicone pads on top & bottom, it can secure your laptop in place and maximum protect your device from scratches and sliding. Moreover, smooth edges will never hurt your hands.
  • ✅【Heat Dissipation】 :The top of the laptop stand is designed with multiple ventilation holes. The open design offers greater ventilation and more airflow to cool your laptop during operation other than it just lays flat on the table.
  • ✅【Portable & Foldable】:The foldable design allows you to easily slip it in your backpack. Ideal for people who travel for business a lot.
  • ✅【Broad Compatibility】:Our laptop holder is compatible with all laptops from 10-17.3 inches, such as MacBook Air/ Pro, Google Pixelbook, Dell XPS, HP, ASUS, Lenovo ThinkPad, Acer, Chromebook and Microsoft Surface, etc.Be your ideal companion in Home, Office & Outdoor.
FXMLLoader loader = new FXMLLoader(
        getClass().getResource("dashboard.fxml"));

loader.setControllerFactory(type -> {
    if (type == DashboardController.class) {
        return new DashboardController(session, navigation);
    }
    try {
        return type.getDeclaredConstructor().newInstance();
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException(e);
    }
});

Parent root = loader.load();

A dependency-injection container can provide the factory as well. A third-party DI framework is optional; for a small application, a callback, setter or directly supplied controller may be simpler.

Open controller packages in modular applications

In a named Java module, the package containing FXML controllers must be reflectively accessible to javafx.fxml. A typical module declaration is:

module com.example.app {
    requires javafx.controls;
    requires javafx.fxml;

    opens com.example.app to javafx.fxml;
    exports com.example.app;
}

The opens directive permits FXML reflection on controller members; add it for other packages containing FXML-loaded types as needed. Without the required access, loading can fail with a reflective-access exception. JavaFX 26 documentation is cited here for the API and FXML behavior; the core pattern applies across JavaFX versions, but check the documentation for the JavaFX version used by your project. See the JavaFX FXML API documentation on reflective access.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Understand controller lifetime when loading repeatedly

Each successful call to load() normally creates a new view graph and controller. Loading dashboard.fxml again does not recover the earlier dashboard controller or its state. If a screen should retain state, keep its loaded root and controller and reuse them; otherwise create a fresh view intentionally. Avoid manually constructing another controller and expecting it to control the loaded FXML.

Fix common FXMLLoader problems

  • getController() is null: Check that the FXML has fx:controller or that you supplied a controller programmatically, that loading succeeded, and that you called getController() on the loader that performed that load.
  • “Location is not set”: The resource lookup likely returned null. Verify the file is packaged under resources, the path is correct relative to the lookup class (or begins with / for an absolute classpath path), and capitalization matches.
  • An @FXML field is null: Confirm the field name matches the FXML fx:id, the private field has @FXML, the expected FXML/controller pair is loaded, and you do not access the field before loading finishes.
  • A field is null in the constructor: FXML injection has not happened yet. Move setup that uses injected controls to initialize() or another method called after load().
  • “Controller value already specified”: Do not combine an FXML fx:controller declaration with loader.setController(...) for the same document.
  • Handler method not found: For onAction="#handleLogin", check the spelling and ensure the controller has an accessible compatible handler, for example an @FXML method accepting no arguments or an ActionEvent.
  • InaccessibleObjectException in a named module: Add requires javafx.fxml; and open the controller package to javafx.fxml in module-info.java.
  • State disappears or duplicate controllers appear: Check whether the FXML is loaded more than once or another controller was manually instantiated. Reuse the loader’s controller instance, or retain and reuse the loaded screen when its state must persist.

Choose a structure that fits the screen

  • Use separate FXML files and controllers for cohesive screens, dialogs and windows with distinct lifecycles.
  • Use fx:include for reusable panels that appear together in one screen.
  • Use a callback for a small one-off action; use shared models or services for state that several views need.
  • Use a parent coordinator for closely related included components, and avoid making unrelated controllers depend directly on each other.
  • Keep business rules in models or services, not in a controller that grows to own the entire application.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.