显示ImageIcon

4

我想在一个JPanel上显示一张图片。我使用ImageIcon来渲染图片,而且图片和类文件在同一个目录下。然而,图片没有被显示出来,也没有发生错误。请问有谁能帮忙找出我的代码哪里出了问题...

package ev;

import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Image extends JPanel {

    ImageIcon image = new ImageIcon("peanut.jpg");
    int x = 10;
    int y = 10;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        image.paintIcon(this, g, x, y);
    }
}
2个回答

4
这是程序员经常感到困惑的问题。 getClass().getResource(path) 从类路径中加载资源。

ImageIcon image = new ImageIcon("peanut.jpg");

如果我们只提供了图像文件的名称,则Java会在当前工作目录中查找它。 如果您正在使用NetBeans,则CWD是项目目录。 您可以使用以下调用在运行时确定CWD:

System.out.println(new File("").getAbsolutePath());

以下是一个代码示例,您可以测试自己的内容。

package com.zetcode;

import java.awt.Dimension;
import java.awt.Graphics;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawingPanel extends JPanel {

    private ImageIcon icon;

    public DrawingPanel() {

        loadImage();
        int w = icon.getIconWidth();
        int h = icon.getIconHeight();
        setPreferredSize(new Dimension(w, h));

    }

    private void loadImage() {

        icon = new ImageIcon("book.jpg");
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        icon.paintIcon(this, g, 0, 0);
    }

}

public class ImageIconExample extends JFrame {

    public ImageIconExample() {

        initUI();
    }

    private void initUI() {

        DrawingPanel dpnl = new DrawingPanel();
        add(dpnl);

        // System.out.println(new File("").getAbsolutePath());         

        pack();
        setTitle("Image");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {                
                JFrame ex = new ImageIconExample();
                ex.setVisible(true);                
            }
        });
    }
}

以下图片显示了如果我们只提供图像名称给ImageIcon构造函数,应将book.jpg图像放在NetBeans中的哪个位置。 Location of the image in NetBeans project 我们从命令行运行相同的程序。我们在ImageIconExample目录中。 $ pwd /home/vronskij/prog/swing/ImageIconExample $ tree . ├── book.jpg └── com └── zetcode ├── DrawingPanel.class ├── ImageIconExample$1.class ├── ImageIconExample.class └── ImageIconExample.java
2 directories, 5 files
使用以下命令运行程序: $ ~/bin/jdk1.7.0_45/bin/java com.zetcode.ImageIconExample 您可以在我的Java显示图像教程中了解更多信息。

2

您应该使用

ImageIcon image = new ImageIcon(this.getClass()
                .getResource("org/myproject/mypackage/peanut.jpg"));

使用getClass().getResource(path) - Yegoshin Maxim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接