I've read the following from her e
https://docs.oracle.com/javase/8/javafx/fxml-tutorial/jfx2_x-features.htm
When a controller factory is provided to the FXMLLoader object, the loader
will delegate controller construction to the factory. An implementation might
return a null value to indicate that it does not or cannot create a controller
of the given type; in this case, the default controller construction mechanism
will be employed by the loader. Implementations might also "recycle"
controllers such that controller instances can be shared by multiple FXML
documents. However, developers must be aware of the implications of doing this:
primarily, that controller field injection should not be used in this case
because it will result in the controller fields containing values from only the
most recently loaded document.
As I understood it is the feature of javafx2. But what about javafx8? I did the
following test:
public class Test1Controller {
@FXML
public Button Test1Button;
@FXML
public void onTest1Button(){
System.out.println("TEST1 BUTTON IS PRESSED"+Test1Button.getText());
}
}
public class Test2Controller extends Test1Controller{
@FXML
public Button Test2Button;
@FXML
private void onTest2Button(){
System.out.println("TEST2 BUTTON IS
PRESSED"+Test2Button.getText()+Test1Button.getText());
}
}
test1.fxml
<AnchorPane maxHeight="-Infinity" fx:id="Test1Pane" maxWidth="-Infinity"
minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/8.0.45" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="temp.Test1Controller">
<children>
<Button fx:id="Test1Button" layoutX="300.0" layoutY="40.0"
mnemonicParsing="false" onAction="#onTest1Button" text="Test1" />
</children>
</AnchorPane>
test2.fxml
the main code:
@Inject
private FXMLLoader fxmlLoader1;
@Inject
private FXMLLoader fxmlLoader2;
private Test2Controller testController=new Test2Controller();
@FXML
private void handleOkButtonAction(ActionEvent event) throws IOException {
Callback<Class<?>, Object> controllerFactory = type -> {
return testController ;
};
fxmlLoader1.setControllerFactory(controllerFactory);
fxmlLoader2.setControllerFactory(controllerFactory);
Parent parent2 = (Parent)fxmlLoader2.load(getFxmlStream("test2.fxml"));
Parent parent1 = (Parent)fxmlLoader1.load(getFxmlStream("test1.fxml"));
mainAnchorPane.getChildren().addAll(parent1,parent2);
As the result - I have two button on anchor pane. However, the Test1Button
doesn't have action handler so it is not clickable. What about Test2Button it
works ok and when I click it I get:
TEST2 BUTTON IS PRESSED Test2 Test1
It means that Test1Button was also injected. Besides I've noticed that if add
firstly to pane parent2 and then parent1 -
mainAnchorPane.getChildren().addAll(parent2,parent1); then
Test1Button works, but Test2Button is not clickable.
Why only one of handlers works? This is a bug in javafx8 or this is limitation?
--
Alex Sviridov