【问题标题】:Open Image from FileChooser in JavaFX在 JavaFX 中从 FileChooser 打开图像
【发布时间】:2026-01-28 04:55:02
【问题描述】:

我的程序应该从文件上传图像,然后将该图像显示为背景。我的问题是,当我在它的参数中创建一个 Image 对象时,它会询问您要放置的文件。我试图将我的 File 对象放在它的参数中,但它不起作用。请帮我。我卡住了。

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);
    }        
}

【问题讨论】:

    标签: java javafx filechooser


    【解决方案1】:

    问题在于Image 的构造函数需要String url,而您传递给它的是File。任何好的 IDE 都会告诉您给定方法期望的参数是什么;找到该键盘快捷键并使用它(IntelliJ 中的 Ctrl + P)。从那里,您所要做的就是找到一种将File 转换为代表其网址的String 的方法。在这种情况下:

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

    请注意,您实际上从未设置背景图像,您需要将以下行添加到您的 lambda:

    stac.setBackground(new Background(backgroundImage));
    

    为此,您必须将 stac 的声明移到您的动作侦听器上方。

    【讨论】: