【问题标题】:Java fx Image pathJavafx 图像路径
【发布时间】:2015-02-19 09:34:58
【问题描述】:
javafx'ImageView 有问题。
我尝试加载一个简单的jpg,作为图像并将其添加到ImageView。
但是Javafx找不到资源。
Image image = new Image("image.jpg");
ImageView iv1_1 = new ImageView();
iv1_1.setImage(image);
我得到的例外是这个:
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
它在创建图像的行中崩溃。
这是项目的图片:
enter link description here
(我不允许发布图片。)
【问题讨论】:
标签:
image
url
path
javafx
【解决方案1】:
这对我有用
Image image = null;
try {
image = new Image(new FileInputStream("image.jpg"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ImageView view = new ImageView();
view.setImage(image);
【解决方案2】:
请在下面找到使用 JavaFX 加载图像的示例。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LoadImage extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Load Image");
StackPane sp = new StackPane();
Image img = new Image("javafx.jpg");
ImageView imgView = new ImageView(img);
sp.getChildren().add(imgView);
//Adding HBox to the scene
Scene scene = new Scene(sp);
primaryStage.setScene(scene);
primaryStage.show();
}
}
在您的项目中创建一个名为 Image 的源文件夹并将您的图像添加到该文件夹中,否则您可以直接从外部 URL 加载图像,如下所示。
Image img = new Image(
"http://mikecann.co.uk/wp-content/uploads/2009/12/javafx_logo_color_1.jpg"
);
【解决方案3】:
使用 getClass().getResource("image.jpg)