我正在嘗試將影像上傳到 java fx 上的影像視圖,當我選擇影像時出現以下錯誤(運行時)。
引起:java.lang.IllegalArgumentException:無效 URL:未知協議:c at javafx.scene.image.Image.validateUrl(Image.java:1121) at javafx.scene.image.Image.(Image.java:620) at me.siyum.schola.controller.AddStudentFromController.uploadStImageOnAction(AddStudentFromController.java:28) ... 41 更多原因:java.net.MalformedURLException:未知協議:c
我正在嘗試的代碼:
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.image.ImageView;
import javafx.scene.shape.Circle;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
public class AddStudentFromController {
public Circle circleImage;
public ImageView imgSt;
public void uploadStImageOnAction(MouseEvent mouseEvent) {
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter(
".IMAGE","jpg", "gif", "png");
jFileChooser.addChoosableFileFilter(fileNameExtensionFilter);
int result = jFileChooser.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = jFileChooser.getSelectedFile();
String absolutePath = selectedFile.getAbsolutePath();
Image img = new Image(absolutePath);
imgSt.setImage(img);
}
}
}
uj5u.com熱心網友回復:
Image
建構式需要 URL 的字串表示形式。要獲取 的 URL File
,請使用selectedFile.toURI().toURL()
。要以穩健的方式轉換為字串表示形式,請呼叫toExternalForm()
. URL
所以你需要
Image img = new Image(selectedFile.toURI().toURL().toExternalForm());
(您幾乎可以肯定地依賴selectedFile.toURI().toString()
;上面的代碼只是感覺更健壯一些。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529599.html
標籤:爪哇javafx
上一篇:用數字多次替換文字