从另一个控制器JavaFx调用方法

时间:2015-11-28 19:52:52

标签: java javafx imageview fxml

RootLayoutControl.java

public class RootLayoutController {

private MainApp mainApp;


 public void setMainApp(MainApp mainApp) {
    // TODO Auto-generated method stub
    this.mainApp = mainApp;
}

@FXML
private void handleNew(){

}

@FXML
private void handleOpen(){
    FileChooser fileChooser = new FileChooser();

    //Set extension filter
    ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Image Files", "*.png","*.jpg", "*.jpeg");

    fileChooser.getExtensionFilters().add(extFilter);

    // Show save file dialog
    File file = fileChooser.showOpenDialog(mainApp.getPrimaryStage());

    if(file != null){
        //CALL createImageView(file);
    }
}

MainApp.java

public class MainApp extends Application {

 private Stage primaryStage;
 private BorderPane rootLayout;

@Override
public void start(Stage primaryStage) {
    this.primaryStage = primaryStage;
    this.primaryStage.setTitle("Photo Album");

    initRootLayout();

    showImageView();
}

private void showImageView() {
    // TODO Auto-generated method stub
    try {
        // Load person overview.
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("ImageView.fxml"));
        AnchorPane imageOverview = (AnchorPane) loader.load();

        ImageViewController controller = loader.getController();
        controller.setMainApp(this);

        // Set person overview into the center of root layout.
        rootLayout.setCenter(imageOverview);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public Stage getPrimaryStage() {
    return primaryStage;
}

public static void main(String[] args) {
    launch(args);
}

public void ShowView(File file) {
    // TODO Auto-generated method stub

}

ImageViewController.java

public class ImageViewController {

private MainApp mainApp;

@FXML
private ImageView imageView;

@FXML
private TilePane tile;

public void setMainApp(MainApp mainApp) {
    // TODO Auto-generated method stub
    this.mainApp = mainApp;
}

private ImageView createImageView(File file){
    return imageView;
}

创建图库,如果我调用该方法,

  

RootLayoutController中的handleOpen()

它会调用方法,

  

ImageViewController中的createImageView()

要将变量文件传递给它,有关如何进行的任何建议?

1 个答案:

答案 0 :(得分:2)

首先,createImageView()方法需要公开。

public ImageView createImageView(File file){
    return imageView;
}

在RootLayoutController中,您需要创建一个方法来获取ImageViewController的实例

private ImageViewController imageView;

public void setImageView(ImageViewController imageView) {
   this.imageView = imageView;
}

然后你需要获取控制器并从RootLayoutController调用setImageView()方法来传递它的实例

FXMLLoader loader = new FXMLLoader(getClass().getResource("RootLayoutController.fxml"));
RootLayoutController controller = loader.getController();
controller.setImageView(imageView);