在JavaFX中从FileChooser打开图像 [英] Open Image from FileChooser in JavaFX

查看:108
本文介绍了在JavaFX中从FileChooser打开图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序应该从文件中上传图像,然后将其显示为背景.我的问题是,当我在参数中创建Image对象时,它会询问您要放置的文件.我试图将我的File对象放入其参数内,但无法正常工作.请帮我.我被卡住了.

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

推荐答案

问题是Image的构造函数期望的是String url,而您要传递的是File.任何优秀的IDE都会告诉您给定方法作为其参数的期望.找到该键盘快捷方式并使用它(IntelliJ中的Ctrl + P).从那里开始,您所要做的就是找到一种将File转换为表示其URL的String的方法.在这种情况下:

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

请注意,您实际上从未设置过背景图片,需要在lambda中添加以下行:

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

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

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

这篇关于在JavaFX中从FileChooser打开图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆