你应该只能使用相对路径
File
宾语:
File imageFile = new File(“images/picture.png”)
</code>
您的
program.jar
将从基目录开始;在创建时
File
object,这是您要传递给构造函数的路径的起点。因此,
new File(“images/picture.png”)
将在“images”子目录中查找pictures.png文件。
获得该文件后,您将需要创建自己的文件
Image
使用该文件的URI:
Image image = new Image(imageFile.toURI().toString());
</code>
这实际上创建了文件的完整绝对路径。
的
样品申请:
</强>
这是一个你可以尝试自己的简单例子。你需要确保你拥有
resources
在输出文件夹(.jar文件所在的位置)中创建的文件夹,以及其中的合适图像文件。
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);
}
}
</code>
无论是在IDE中运行应用程序还是在构建JAR或JavaFX应用程序之后,这都将起作用。