javafx:imageview无法加载由程序本身创建的图像错误:java.lang.illegalargumentexception:

g9icjywg  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(350)

我正在尝试创建一个程序,在该程序中,用户从计算机上的不同文件夹中选择一个图像,javafx将该图像复制到项目目录中以供将来使用。将创建一个新文件夹来存储新创建的图像文件。这基本上就是选择图像并将其复制到项目目录中的代码:

Stage window = (Stage) ap.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Image File");
File selectedFile = fileChooser.showOpenDialog(window);

//Creates a new directory for the new calendar that the user wants to create
File file = new File("src/DefaultUser/" + nameField.getText() + "/");
file.mkdir();

//Creates a new file name with logo as the name, but keeping the extension the same
int index = selectedFile.getName().lastIndexOf(".");
String ext = selectedFile.getName().substring(index);

//Stored in newFileName
String newFileName = "logo" + ext;

File newFile = new File(file.getPath() + "/" + newFileName);

//Copies the selected file into the project src folder, with newFileName as the new file name
Files.copy(selectedFile.toPath(), newFile.toPath());

然后程序移动到不同的场景,因此不同的控制器实际将图像加载到imageview中。我知道图像的路径工作正常,但无论出于何种原因,程序都无法找到图像文件将其加载到imageview中。
下面是基本的代码:

image.setImage(new Image("DefaultUser/" + imagePath));

在这种情况下,不要担心imagepath是什么,因为我绝对肯定它指向新创建的图像文件的正确位置。这是因为如果我关闭javafx程序并重新运行它,图像将正确加载。
一开始,我认为这是因为它需要时间的形象被复制到项目目录,但我检查,该文件实际上存在于代码中,它这样做,显然不是这样的。我尝试使用thread.sleep()将程序延迟一点,这样代码可能有更多的时间来复制文件,但仍然抛出相同的错误: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found 最奇怪的是,这个程序运行得非常好,只是我必须重新启动javafx程序才能检测到图像文件,即使我知道它存在。javafx和创建新文件并在同一个程序中访问它们有什么奇怪的地方吗?我真的迷路了。提前非常感谢您的帮助,我很抱歉,如果这不能提供足够的信息,因为我不想解释整个项目。

nfzehxib

nfzehxib1#

就像haraldk和james在评论中说的,把东西放到src文件夹通常是个坏主意。我通过将文件夹移到项目目录中解决了这个问题。

相关问题