r/JavaFX • • Feb 29 '24

Help Use custom controls with markup instead of fx:include?

Starting to get into JavaFX and love it! Been getting into creating custom controls but am finding a pattern I am not too fond of. As far as my knowledge goes, the way you use custom controls in FXML is to us fx:include source="custom-control.fxml" , which really gets annoying to use. I would rather use my control name as the element, just as you would with HTML markup, which looks much nicer in my opinion.

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane xmlns:fx="http://javafx.com/fxml">
    <fx:include source="custom-control.fxml"/>
    vs
    <CustomControl/>
</BorderPane>

I already know how to do this in code but I would much rather not have to go down that route (mixing methodologies). Is there a way to use custom controls the same you would FXML markup?

I found this Oracle tutorial on creating custom controls and in the last example they show using the component just as I described but don't explain how at all (I realize the tutorial is super old and outdated).

Thank you much!

3 Upvotes

36 comments sorted by

View all comments

Show parent comment

1

u/Devirichu Mar 03 '24

What I do NOT think you can do is to create a class in the project in which you are going to reference that class in FXML. So you pretty much have to create a separate Jar file with your custom Node classes.

That's incorrect. It's called a "custom component," and is outlined here: https://docs.oracle.com/javase/8/javafx/fxml-tutorial/custom_control.htm

It's a lot more useful than you might initially think.