在JavaFX中从FileChooser打开图像
我的程序应该上传一个文件中的图像,然后将该图像显示为背景。我的问题是,当我在它的参数中创建一个在JavaFX中从FileChooser打开图像,java,javafx,filechooser,Java,Javafx,Filechooser,我的程序应该上传一个文件中的图像,然后将该图像显示为背景。我的问题是,当我在它的参数中创建一个图像对象时,它会请求您尝试放置的文件。我试图将我的文件对象放入其参数中,但它不起作用。请帮帮我。我卡住了 public class FileOpener extends Application{ public void start(final Stage stage) { stage.setTitle("File Chooser Sample"); final
图像
对象时,它会请求您尝试放置的文件。我试图将我的文件对象放入其参数中,但它不起作用。请帮帮我。我卡住了
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);
}
}
问题是
图像
的构造函数需要一个字符串url
,而您正在向它传递一个文件
。任何好的IDE都会告诉您给定方法的参数是什么;找到键盘快捷键并使用它(IntelliJ中的Ctrl+P)。从这里开始,您所要做的就是找到一种方法,将文件
转换为表示其url的字符串。在这种情况下:
Image image1 = new Image(file.toURI().toString());
请注意,您从未实际设置背景图像,您需要将以下行添加到lambda:
stac.setBackground(new Background(backgroundImage));
但是,为此,您必须将stac
的声明移到动作侦听器上方。问题是图像的构造函数需要一个字符串url
,而您要传递的是一个文件。任何好的IDE都会告诉您给定方法的参数是什么;找到键盘快捷键并使用它(IntelliJ中的Ctrl+P)。从这里开始,您所要做的就是找到一种方法,将文件
转换为表示其url的字符串。在这种情况下:
Image image1 = new Image(file.toURI().toString());
请注意,您从未实际设置背景图像,您需要将以下行添加到lambda:
stac.setBackground(new Background(backgroundImage));
但是,为此,您必须将stac
的声明移到动作侦听器上方