Reputation: 51
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?
Upvotes: 3
Views: 140
Reputation: 297
Basically, in JavaFX Control
don't work like that, it always need a Skin<C>
in order to render.
Try this:
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
.
Upvotes: 1