I have the following code which can be nicely imported in Scene Builder:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<fx:root type="javafx.scene.layout.VBox"
xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/18">
<TextField fx:id="textField" text="Default"/>
<Button onMouseClicked="#doSomething" text="Click Me"/>
</fx:root>
package client.components;
import javafx.beans.property.StringProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import java.io.IOException;
import java.net.URL;
public class MySwitch extends VBox {
@FXML
private TextField textField;
public MySwitch(){
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/client/components/MySwitch.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(MySwitch.this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
// you have to make getters and setters to create an input field of a component
public String getAsd() {
return asdProperty().get();
}
public void setAsd(String value) {
asdProperty().set(value);
}
public StringProperty asdProperty() {
return textField.textProperty();
}
@FXML
public void doSomething() {
System.out.println("The button was clicked!");
}
}
The problem with this approach is that in my MySwitch.fxml, the editor (IntelliJ) only assumes that the root is a VBox, not a MySwitch insance, so it marks #doSomething
with red. However, when I change VBox to MySwitch, there is nice autocompletion and everything seems to still run perfectly. In this case though, Scene Builder cannot import the file, it complains about the class not being found. I tried debugging Scene Builder and it seems that inside exploreEntry
, the catch block with CANNOT_INSTANTIATE is called for my component. How could I achive that I have the best of both worlds (IntelliJ & SceneBuilder working at the same time)?
My fxml file after changing it to MySwitch:
<?xml version="1.0" encoding="UTF-8"?>
<?import client.components.MySwitch?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<fx:root type="client.components.MySwitch"
xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/18">
<TextField fx:id="textField" text="Default"/>
<Button onMouseClicked="#doSomething" text="Click Me"/>
</fx:root>