2012-04-10 43 views
3

我想在JPanel上显示图像。我使用ImageIcon来渲染图像,并且该图像与类文件位于同一目录中。但是,图像没有被显示,并且没有发生错误。任何人都可以请工作了协助有什么错我的代码...显示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

您应该使用

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

对不起,是一个错字 使用getClass()。getResource(path) – 2012-04-10 14:07:50

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

下图为放在哪里book.jpg 图像在NetBeans中,如果我们只提供图像名称 到ImageIcon构造。

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

你可以找到更多我Displaying image in Java教程。