图像加载的路径

时间:2012-01-25 11:13:30

标签: java image swing paintcomponent application-resource

我想在一个帧中添加一个图像但是我无法理解我应该保留图像文件的位置以及我应该如何给出图像的路径?

我已将图片放在My Document文件夹中并给出该路径,但它给出了错误消息。

我有以下代码。

import java.awt.*; 
import java.awt.image.BufferedImage; 
import java.io.*; 
import javax.imageio.ImageIO; 
import javax.swing.*;   

public class Test extends JPanel {
    BufferedImage image;

    public Test(BufferedImage image) {
        this.image = image;
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // Draw image centered.
        int x = (getWidth() - image.getWidth())/2;
        int y = (getHeight() - image.getHeight())/2;
        g.drawImage(image, x, y, this);
    }

    public static void main(String[] args) throws IOException {
        String path = "images.jpeg";
        BufferedImage image = ImageIO.read(new File(path));
        Test contentPane = new Test(image);
        // You'll want to be sure this component is opaque
        // since it is required for contentPanes. Some
        // LAFs may use non-opaque components.
        contentPane.setOpaque(true);
        contentPane.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5,5,5,5);
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        // Add components.
        for(int j = 0; j < 8; j++) {
            gbc.gridwidth = ((j+1)%2 == 0) ? GridBagConstraints.REMAINDER
                                           : GridBagConstraints.RELATIVE;
            contentPane.add(new JButton("button " + (j+1)), gbc);
        }
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(contentPane);
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
    } }

2 个答案:

答案 0 :(得分:9)

您的图片的位置很少。

  • 相对路径,在您的示例中,启动的应用程序在您启动它的文件夹中查找图像(请检查应用程序是否已启动)。您可以通过"resources\\images.jpeg"

  • 为图片和访问创建文件夹“资源”
  • 绝对路径,类似于"C:\\Documents and settings\\<username>\\My Documents\\images.jpeg"

  • classpath - 将图像放在相同的文件夹/包中,放置了Test类。此资源可以打包到.jar文件。

    BufferedImage image = ImageIO.read(Test.class.getResourceAsStream("images.jpeg"));

  • 任何有效的网址,例如您的头像

    BufferedImage image = ImageIO.read(URI.create("http://www.gravatar.com/avatar/d5f91983a9d9cfb69981b6108a63b412?s=32&d=identicon&r=PG").toURL());

答案 1 :(得分:6)

  

我应该在哪里保留图片文件..

由于它看起来像是一个“应用程序资源”,我会说它放在应用程序的运行时类路径上。这通常可以通过在Jar中添加(例如images目录)来实现。

  

..我应该如何给出图像的路径?

通过以下网址访问它:

URL urlToImage = this.getClass().getResource("/images/the.png");

ImageIO.read()也可以接受URL或更多才多艺,InputStream