java - 图片加载路径

标签 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);
    } }

最佳答案

您的图片位置不多。

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

  • 绝对路径,类似"C:\\Documents and settings\\<username>\\My Documents\\images.jpeg"

  • 类路径 - 将图像放在同一个文件夹/包中,您的测试类就在那里。该资源可以打包成.jar文件。

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

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

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

关于java - 图片加载路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9001754/

相关文章:

java - 在 Swing 中的按钮单击事件上打开 WebTabbedPane 上的选项卡。?

Java 为什么我需要最小化然后重新加载?

delphi - 如何判断Tpicture是否包含Jpeg?

java utf-8编码字符串中奇数个字符的字节变化

algorithm - 我想知道像 tineye.com 这样的反向图像搜索服务是如何工作的……?

java - 调整图像大小以适合 JLabel

swing - Java Swing : Open source Gantt chart library

java - 有没有办法从同一个类中的另一个方法在 JPanel 上绘制形状?

java - 在java中确定上传文件的文件类型/扩展名

java - AndEngine:让 Sprite 同时移动和跳跃?