无效的图片网址

时间:2018-03-12 02:58:26

标签: java image javafx

我似乎无法使用Image类。我的同事和我正在一起开展一个项目,他似乎能够毫无错误地运行所有代码。当我尝试运行相同的代码时,src以相同的方式组织,我得到一个无效的URL或资源未找到错误。我在其他项目上遇到过这个问题,看起来它特定于我的计算机或文件系统。任何帮助将非常感激。以下是代码示例。

    public class HomePageGUI extends Application {

//Create the dispenser. Generates 5 Products in an array within the dispenser class.
private final Dispenser dispenser = new Dispenser();
//Get background image and add it to the stack pane
private final Image bgImage = new Image("/Dispenser Design/Background & Button Images/Background.png");
private final Button backButton = new Button("", new ImageView(
      new Image("/Dispenser Design/Background & Button Images/Navigation Buttons/Back Button.png")));
private StackPane backgroundPane = new StackPane();
private Scene scene;

@Override
public void start(Stage primaryStage) {
    primaryStage = homePage(primaryStage);
    primaryStage.show();
}

//Display the home page
private Stage homePage(Stage stage) {

    //IMAGE CREATION
    Image drinksCategoryImage = new Image (
          "/Dispenser Design/Background & Button Images/Starter Page/Drinks Button.png");

    Image gumCategoryImage = new Image (
          "/Dispenser Design/Background & Button Images/Starter Page/Gum Button.png");

    Image sweetsCategoryImage = new Image (
          "/Dispenser Design/Background & Button Images/Starter Page/Sweets Button.png");
    //END IMAGE CREATION

    //Create the buttons with the image displayed on them.
    Button drinksCategoryButton = new Button(
          "", new ImageView(drinksCategoryImage));
    drinksCategoryButton.setOnAction(e -> {
        drinksCategory(stage); });

    Button gumCategoryButton = new Button(
          "", new ImageView(gumCategoryImage));
    gumCategoryButton.setOnAction(e -> {
        gumCategory(stage); });

    Button sweetsCategoryButton = new Button(
          "", new ImageView(sweetsCategoryImage));
    sweetsCategoryButton.setOnAction(e -> {
        sweetsCategory(stage); });
    //END BUTTON CREATION

1 个答案:

答案 0 :(得分:0)

好的,经过几个小时的故障排除后,我发现我需要将文件添加到图像路径中。我不确定为什么我的同事不需要添加文件:扩展以使图像工作,但这就是它最终为我工作的方式。

    productsForSale[ 4] = new Gum("Wriggleys", "Big Red", .75, 1, new Image(
      "file:src/DispenserDesign/IndividualProducts/BigRedGum.jpg"));