我正在尝试使用一个按钮将图像添加到gridview,该按钮会打开仅接受图像的文件选择器。即时通讯使用Filechooser的文件路径创建setImage到我的网格视图时出现异常错误。我认为这是因为获得的路径不正确。
这是失败的代码:
public void makeBrowseButton(Stage primaryStage) {
//attach handler
browseButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
FileChooser fileChooser = new FileChooser(); // create object
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")); //filter for music files
//FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
if ( !parentPath.equalsIgnoreCase("")) { //go to previous directory if exists
File parentPathFile = new File(parentPath);
fileChooser.setInitialDirectory(parentPathFile);
}
File selectedFile = fileChooser.showOpenDialog(primaryStage);
if (selectedFile != null) { // display the dialog box
String wholePath = selectedFile.getPath();
String name = selectedFile.getName();
String megaPath = selectedFile.getAbsolutePath();
parentPath = selectedFile.getParent();
System.out.println("wholePath: " + wholePath);
System.out.println("File Name: " + name);
System.out.println("megaPath: " + megaPath);
Image newAwesomeImage = new Image(megaPath);
ImageView view = new ImageView();
view.setImage(newAwesomeImage);
paneofgridmonkeys.add(view, 0, 0);
//paneofgridmonkeys.add(new Label("Changed the image!"), 0, 1);
createDisplay(primaryStage);
}}});
}
错误消息的标题是确切的问题所在行:
view.setImage(newAwesomeImage);
至于我的system.out结果,这就是我得到的:
wholePath: M:\Home\BenStillerDuckFace.jpg
File Name: BenStillerDuckFace.jpg
megaPath: M:\Home\BenStillerDuckFace.jpg
ive尝试了所有这些方法,但都没有用。有什么想法吗?
答案 0 :(得分:2)
Image(String url)
构造函数需要URL字符串,而不是文件名。文件名不是URL。
要将文件名字符串转换为URL字符串,请执行以下操作之一:
// Java 7+
String megaUrl = Paths.get(megaPath).toUri().toURL().toString();
// Java 1.4+
String megaUrl = new File(megaPath).toURI().toURL().toString();