无法读取输入文件

时间:2014-03-11 06:31:42

标签: java image window jframe

我正在尝试在我的程序中显示图像,但我遇到了一些困难。

public static BufferedImage background;
public static void main(String[] args) {    
    try {
        background = ImageIO.read(new File("background.jpg"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    Display game = new Display();
    JFrame frame = new JFrame();
    JLabel label = new JLabel(new ImageIcon());
    frame.add(game);
    frame.add(label);
    frame.pack();
            // JFrame configurating
}

程序无法从指定的路径读取文件。这是包浏览器: package explorer

感谢任何帮助:)

2 个答案:

答案 0 :(得分:1)

默认位置是项目文件夹"EasyAdmin"。但是您的图片位于名为"Images"的文件夹中,因此您必须指定它:

background = ImageIO.read(new File("Images\\background.jpg"));

答案 1 :(得分:0)

我说图像是应用程序的一部分。你设置项目的方式,它是你的类路径的一部分,这是一个好主意。这意味着你应该加载它:

URL url = Thread.currentThread().getContextClassLoader().getResource("background.jpg");
background = ImageIO.read(new File(url.toURI()));