我很难在罐子外面访问图像源。我正在为画布加载图像,当图像位于jar内时,该画布没有问题。
但现在我想创造……
你应该只能使用相对路径 File 宾语:
File
File imageFile = new File("images/picture.png")
您的 program.jar 将从基目录开始;在创建时 File object,这是您要传递给构造函数的路径的起点。因此, new File("images/picture.png") 将在“images”子目录中查找pictures.png文件。
program.jar
new File("images/picture.png")
获得该文件后,您将需要创建自己的文件 Image 使用该文件的URI:
Image
Image image = new Image(imageFile.toURI().toString());
这实际上创建了文件的完整绝对路径。
的 样品申请: 强>
这是一个你可以尝试自己的简单例子。你需要确保你拥有 resources 在输出文件夹(.jar文件所在的位置)中创建的文件夹,以及其中的合适图像文件。
resources
import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.io.File; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ // Just a box to put our image in VBox root = new VBox(); root.setPadding(new Insets(10)); root.setAlignment(Pos.CENTER); // Create our image. It is located in the "resources" folder of our application. We will first create a File // to represent the external resource. File imageFile = new File("resources/icon.png"); Image image = new Image(imageFile.toURI().toString()); // Add our image/ImageView to the scene root.getChildren().add(new ImageView(image)); primaryStage.setTitle("External Images"); primaryStage.setScene(new Scene(root, 300, 275)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
无论是在IDE中运行应用程序还是在构建JAR或JavaFX应用程序之后,这都将起作用。