Open Image from FileChooser in JavaFX

人盡茶涼 提交于 2019-12-19 11:31:36

问题


My program is supposed to upload a image from a file and then it displays that image as the background. My problem is that when I create an Image object in it's parameters it asks for the file which you are trying to put. I tried to putting my File object inside of its parameters and it's not working. Please help me. I'm Stuck.

public class FileOpener extends Application{

    public void start(final Stage stage) {
        stage.setTitle("File Chooser Sample");

        final FileChooser fileChooser = new FileChooser();

        final Button openButton = new Button("Choose Background Image");
        openButton.setOnAction((final ActionEvent e) -> {
            File file = fileChooser.showOpenDialog(stage);
            if (file != null) {
               // openFile(file);

               // where my problem is 
                Image image1 = new Image("file");
                // what I tried to do
                    // Image image1 = new Image(file);
                ImageView ip = new ImageView(image1);
                BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, false);
                BackgroundImage backgroundImage = new BackgroundImage(image1, BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize);
            }
        }); 
        final StackPane stac = new StackPane();       
        stac.getChildren().add(openButton);
        stage.setScene(new Scene(stac, 500, 500));
        stage.show();
    }  

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

回答1:


The problem is that the constructor of Image is expecting a String url, whereas you're passing it a File. Any good IDE will tell you what a given method is expecting as its parameters; find that keyboard shortcut and use it (Ctrl + P in IntelliJ). From there, all you have to do is find a way to convert a File to a Stringrepresenting its url. In this case:

Image image1 = new Image(file.toURI().toString());

Note that you are never actually setting your background image, you need to add the following line to your lambda:

stac.setBackground(new Background(backgroundImage));

For this though, you will have to move the declaration of stac above your action listener.



来源:https://stackoverflow.com/questions/41927994/open-image-from-filechooser-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!