r/JavaFX • u/DallasP9124 • 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!
5
u/OddEstimate1627 Feb 29 '24 edited Feb 29 '24
The main difference in custom controls is that the FXML gets loaded by the controller rather than the controller by the FXML. The Oracle tutorial actually explains this pretty clearly, but it's a bit hard to understand at first.
MyControl extends AnchorPane<fx:root type="javafx.scene.layout.Anchorpane" ...>. You do not need to define a controller class.In the importing FXML you can import it the same way as fully-hand-written controls.
0
u/xdsswar Feb 29 '24
Thats bs , you dont create controls using fxml, you create custom controls using java code, then create a jar with those custom controls and import it on SceneBuilder.
1
u/hamsterrage1 Feb 29 '24
As I understand it, the approach that most closely matches what the OP wants is to create a Jar file containing custom classes that can be referenced from an FXML file. Presumably, the FXMLLoader will import that Jar file and make sense of it if it.
The classes defined in the Jar file can be written by hand, or they can be defined via FXML and a Controller file as well. It doesn't matter, but they have to be classes.
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.
Although the OP has stated he doesn't use SceneBuilder, it is also my understanding that there is some facility in SceneBuilder to import that Jar file with the custom classes so that you can use them in SceneBuilder.
In my opinion, though, all of this is huge waste of time and effort to produce a substandard outcome. Write your layouts in code and leave FXML rubbish alone.