[英]How to get specific instance of controller from parent controller at JavaFX2?
我有2个fxml布局,其中一个包含另一个。 我尝试从父控制器更新内部元素的内容,即当按下父控制器上的按钮时,在imageview上更改图像。
我使用这里提出的方法。 问题是当我调用假设要更改imageView内的图像的方法时( questionController.setPdfPageImage(++currentPage);
),什么都没有发生。 我尝试了一些调试,我相信这是因为有两个完全不同的控制器实例:默认情况下,一个是从运行时调用的,另一个是从fxml调用的。 请指出正确的解决方案。
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>
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>
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);
}
}
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();
}
});
}
}
要注入包含的fxml的控制器,请将fx:id
属性添加到fx:include
标记中:
<fx:include fx:id="question" source="question.fxml"/>
这会将控制器注入到名称为<fx:id>Controller
的字段中,在这种情况下(即,如果加载程序可见此字段的话)为questionController
。
(也可以从initialize
方法中删除加载器部分)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.