2017-01-30 56 views
0

我的程序应该从文件上载图像,然后将该图像显示为背景。我的问题是,当我在它的参数中创建一个Image对象时,它会询问您正在尝试放置的文件。我试图把我的File对象放在它的参数中,它不起作用。请帮帮我。我困了。从JavaFX中的FileChooser打开图像

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

回答

3

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

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

注意,你从来没有真正设置你的背景图片,你需要将下面的行添加到您的拉姆达:

stac.setBackground(new Background(backgroundImage)); 

对于这虽然,你将不得不动声明stac高于您的动作侦听器。