【问题标题】:I can't load an image in Javafx我无法在 Javafx 中加载图像
【发布时间】:2017-01-03 17:51:54
【问题描述】:

我在 stackoverflow 中阅读了许多其他关于此的主题,但他们的解决方案似乎都不适合我的问题。没有错误,只是一个空白阶段,我不明白为什么。

public void titleView(Pane pane)
{
    Image img = new Image("file:test.png");

    ImageView title = new ImageView(img);
    title.setImage(img);
    title.setLayoutX(569);
    title.setLayoutY(146);
    title.fitHeightProperty().add(100);
    title.fitWidthProperty().add(100);
    title.setVisible(true);

    pane.getChildren().add(title);

    System.out.println("success!!!");        
}

这是我做的方法。 “test.png”文件只是一张用油漆制成的红色 100x100 图片。它位于项目和我创建的文件夹中:res/textures/test.png 我确实记得为它建立路径

Pane pane = new Pane();
titleView(pane);

希望有人能帮忙,谢谢

【问题讨论】:

  • 项目建成后相对于您的类路径的实际路径是什么? (例如,如果您将 res 作为构建路径的一部分,那么您应该能够在构建文件夹和/或 jar 文件中看到 textures/test.png)。这里的最终目标是什么?这些图像会与应用程序捆绑在一起吗?或者您打算从用户文件系统上的某个位置加载它们(例如,通过文件选择器,或在应用程序外部的某个指定文件夹中)?

标签: java image javafx imageview


【解决方案1】:

试试这个.getResourceAsStream

Image image = new Image(getClass().getResourceAsStream("pic.png"));
 title.setImage(image);

getClass().getResource("...") 还会在 Netbeans 中抛出 NPE。

【讨论】:

    【解决方案2】:

    这一切都与您的文件路径引用有关...

    Image img = new Image(YourMainClassName.class.getClass().getResource("test.jpg").toString());
    

    或类似的可能工作

    【讨论】:

    • 我尝试了这个和其他一些变体,但似乎没有一个有效。我每次都会得到一个 java.lang.NullPointerException。
    • 使用此方法,图像必须与YourMainClassName 位于同一位置(即在默认包或src 文件夹中)
    • 我指望使用很多图像,然后它会变得非常混乱。但是我还是试了一下,还是得到了 java.lang.NullPointerException
    【解决方案3】:

    我经常遇到这个问题。我开始解决它的方法是确保文件退出。很多时候基本上是文件路径错误。

    试试:

        File file = new File("YourFile.jpg");
        if(file.exists())
        {
            System.out.println("file exist!");//I would print file path here.
        }
        else
        {
            System.out.println("file does not exist!");
        }
    

    如果文件没有退出,请使用你的文件路径:File file = new File("src/img/YourFile.jpg");

    如果文件退出,其他提到的方法之一应该可以工作。

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多