Reputation: 435
How do you define your own custom control in JavaFX?
Say I have a custom control, for the sake of simplicity, let's just make it a VBox
with two Button
in it, and call the whole thing CustomButton
.
CustomButton.fxml
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.VBox?>
<VBox>
<Button text="Custom Button A"/>
<Button text="Custom Button B"/>
</VBox>
Now say my root layout looks like this, I especially want to be able to use the CustomButton
just as if it was a Label
or a regular Button
.
MainView.fxml
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.Button?>
<HBox>
<Button text="Main Button"></Button>
<CustomButton />
</HBox>
Main.java
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("MainView.fxml"));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Currently, this results in
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: javafx.fxml.LoadException: CustomButton is not a valid type.
What do I have to change in order to use my CustomButton
as a proper control?
Upvotes: 2
Views: 7809
Reputation: 1776
I think this question has already an answer here CustomControl, for the answer, in order to use a custom component in your FXML you have to include it with the expression fx:include
inside your container for exemple :
<fx:include source="CustomButton.fxml"/>
in this case the component is added graphically you can handle it with his own controller, here is the tutoriel fx:include
Upvotes: 1