I have 2 fxml layouts, one of which includes another. I try to update contents of inner element from controller of parent, i. e. when button at parent controller is pressed change image at imageview.
I use approach, proposed here. The problem is when I call method that suppose to change image inside the imageView (questionController.setPdfPageImage(++currentPage);
), nothing happens. I tried some debugging and I believe that is because there are two completely different controller instances: one that is called from runtime and another that is called from fxml by default. Please point me to the right solution.
part of main.fxml
<BorderPane
fx:id="mainContainer"
xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.package.name.MainController">
<center>
<Pane fx:id="center">
<fx:include source="question.fxml"/>
</Pane>
</center>
<bottom>
<VBox fx:id="bottom"
BorderPane.alignment="CENTER">
<children>
<Button fx:id="next" text="Next"/>
</children>
</VBox>
</bottom>
</BorderPane>
part of question.fxml
<SplitPane fx:id="content"
dividerPositions="0.5"
xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.package.name.QuestionController">
<items>
<AnchorPane fx:id="questionContainer">
<children>
<ImageView fx:id="questionView" pickOnBounds="true" preserveRatio="true"/>
</children>
</AnchorPane>
</items>
</SplitPane>
part of QuestionController.java
public void setPdfPageImage(int pageNum) {
// InputStream is = QuestionController.class.getResourceAsStream(currentPdf);
InputStream is = this.getClass().getResourceAsStream(currentPdf);
Image convertedImage;
try {
PDDocument document = PDDocument.load(is);
List<PDPage> list = document.getDocumentCatalog().getAllPages();
PDPage page = list.get(pageNum);
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 128);
convertedImage = SwingFXUtils.toFXImage(image, null);
document.close();
questionView.setImage(convertedImage);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
part of MainController.java
public class MainController implements Initializable {
QuestionController questionController;
@FXML // fx:id="next"
private Button next; // Value injected by FXMLLoader
@Override
public void initialize(URL location, ResourceBundle resources) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/question.fxml"));
try {
loader.load();
} catch (IOException e1) {
e1.printStackTrace();
}
questionController = (QuestionController) loader.getController();
next.setOnAction(event -> {
//TODO remove hardcoded value 49
if (currentPage < 49)
questionController.setPdfPageImage(++currentPage);
else {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Quiz finished");
alert.setHeaderText(null);
alert.setContentText("This was the last question. Thank you!");
alert.showAndWait();
}
});
}
}