从按钮上的FileChooser打开图像

时间:2018-01-03 20:04:03

标签: javafx

enter image description here我需要帮助我想在javafx上使用filechooser打开带有浏览按钮的图像?我怎么能这样做?

 FileChooser f;
File file;
Image img;
ImageView mv;

@Override
public void start(Stage primaryStage) 
{

    f = new FileChooser();
    Button browse = new Button("Browse");

    browse.setOnAction((event) -> 
    {
         file = f.showOpenDialog(primaryStage);
         img  = new Image(file.toURI().toString());
         mv   = new ImageView(img);

    });
         mv.setImage(img);
        BorderPane root = new BorderPane();
    root.setTop(browse);
    root.setCenter(mv);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

1 个答案:

答案 0 :(得分:1)

start方法设置场景并显示窗口。它在按钮处理程序运行之前完成,并且此时在执行期间获得的信息不可用。您需要使用事件处理程序中的图像修改场景,原因如下:

@Override
public void start(Stage primaryStage) {

    final FileChooser f = new FileChooser();
    final ImageView mv = new ImageView(); // create empty ImageView
    Button browse = new Button("Browse");

    browse.setOnAction((event) -> {
         File file = f.showOpenDialog(primaryStage);
         if (file != null) { // only proceed, if file was chosen
             Image img = new Image(file.toURI().toString());
             mv.setImage(img);
         }

    });

    BorderPane root = new BorderPane();
    root.setTop(browse);
    root.setCenter(mv);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

或者,您可以在事件处理程序中创建ImageView并将其放在场景中:

@Override
public void start(Stage primaryStage) {

    final FileChooser f = new FileChooser();
    Button browse = new Button("Browse");
    final BorderPane root = new BorderPane();

    browse.setOnAction((event) -> {
         File file = f.showOpenDialog(primaryStage);
         if (file != null) { // only proceed, if file was chosen
             Image img = new Image(file.toURI().toString());
             ImageView mv = new ImageView(img);
             root.setCenter(mv); // add ImageView to scene
         }

    });

    root.setTop(browse);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}