Created
December 25, 2017 07:05
-
-
Save kokobd/8e1334773b5cc991959e99b589990685 to your computer and use it in GitHub Desktop.
Load FXML for custom JavaFX component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javafx.fxml.FXMLLoader; | |
import javafx.scene.Parent; | |
import java.io.IOException; | |
public final class FXMLUtil { | |
/** | |
Suppose you want to create a custom component called MyComponent. | |
You create a class named MyComponent and an FXML file named MyComponent.fxml, | |
then call this method to load the FXML file within MyComponent's constructor | |
and sets MyComponent as the controller. | |
See https://zelinf.github.io/posts/java/2017-12-19-javafx-custom-component.html | |
if you want to know more. | |
*/ | |
public static <T extends Parent> void loadFXML(T component) { | |
FXMLLoader loader = new FXMLLoader(); | |
loader.setRoot(component); | |
loader.setControllerFactory(theClass -> component); | |
String fileName = component.getClass().getSimpleName() + ".fxml"; | |
try { | |
loader.load(component.getClass().getResourceAsStream(fileName)); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment