Use Custom Control in FXML Document
Use Custom Control in FXML Document
How can I use a custom control in a FXML document? I know here are many answers about that, but all examples extends from existing controls like buttons, labels or even panels. But I extend from the 'Control' class and it don't work.
public class MyControl extends Control {
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.Scene?>
<?import javafx.scene.layout.Pane?>
<?import .MyControl?>
<Scene xmlns:fx="http://javafx.com/fxml/1">
<width>800</width>
<height>600</height>
<Pane fx:id="pane">
<MyControl></MyControl>
</Pane>
</Scene>
If I extend from any other control like a button or something, it works fine. What I need to do?
This don't really help. If you look in the example codes, they extend from other existing controls. I'm writing a full control from scratch. On this page they use a VBox... | I used google before too. After hours of research I finally asked here.
– Cederik Althaus
Jul 2 at 12:08
Define "Does not work". What does the exception say? Does fixing the import work (you probably should move the class to some package other than the default package anyways). If there is no exception, describe what's wrong. (I guess there is no visual result on screen...)
– fabian
Jul 2 at 12:42
@CederikAlthaus Try this site guigarage.com/2012/11/custom-ui-controls-with-javafx-part-1. guigarage.com/2012/11/custom-ui-controls-with-javafx-part-2
– Sedrick
Jul 2 at 13:24
1 Answer
1
Basically, in JavaFX Control
don't work like that, it always need a Skin<C>
in order to render.
Try this:
Control
Skin<C>
import javafx.scene.control.Control;
import javafx.scene.control.Skin;
import javafx.scene.control.SkinBase;
import javafx.scene.layout.Pane;
public class MyControl extends Control {
@Override
protected Skin<?> createDefaultSkin() {
return new SkinBase<MyControl>(this) {
{
Pane pane = new Pane();
pane.prefWidthProperty().bind(getSkinnable().prefWidthProperty());
pane.prefHeightProperty().bind(getSkinnable().prefHeightProperty());
pane.setStyle("-fx-background-color: red");
getChildren().add(pane);
}
};
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.Scene?>
<?import javafx.scene.layout.Pane?>
<?import MyControl?>
<Scene xmlns:fx="http://javafx.com/fxml/1">
<width>800</width>
<height>600</height>
<Pane fx:id="pane">
<MyControl prefWidth="500" prefHeight="500"></MyControl>
</Pane>
</Scene>
But this is just an example. You should explore better ways to create custom Controls, check for createDefaultSkin()
in regular classes like Button
and Checkbox
.
createDefaultSkin()
Button
Checkbox
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I found this: docs.oracle.com/javafx/2/fxml_get_started/custom_control.htm
– ncmathsadist
Jul 2 at 12:05