日期:2014-05-20  浏览次数:20657 次

如何在已生成的jpanel上面添加图片
public class ImageViewer extends JPanel{
  static Image srcImage;
  static int dstwidth=0;
  static int dstheight=0;
  public ImageViewer(String ImageFileName) {
  ImageIcon imageIcon=new ImageIcon("ImageFileName");
  srcImage=imageIcon.getImage();
  int srcwidth=srcImage.getWidth(null);
  int srcheight=srcImage.getHeight(null);
  int maxsize=100;
  dstwidth=srcwidth;
  dstheight=srcheight;
  float k=0;
  if(srcwidth>maxsize){
  dstwidth=maxsize;
  k=(float)srcwidth/(float)maxsize;
  dstheight=Math.round((float)srcheight/k);
  }
  srcheight=dstheight;
  if(srcheight>maxsize){
  dstheight=maxsize;
  k=(float)srcheight/(float)maxsize;
  dstwidth=Math.round((float)dstwidth/k);
  }
  }
  public void paintComponent(Graphics g){
  super.paintComponent(g);
  if(srcImage !=null){
  g.drawImage(srcImage,0,0,dstwidth , dstheight, this);
  }

  }

}
情况是这样的,想要做一个图片查看器,在jframe上面添加了一个jpanel1,然后用jpanel1.add(new ImageViewer("图片路径"))想在jpanel上面显示出图片的缩略图,可是显示不出来,小弟刚学java不久,希望各位大牛能够帮帮忙,最好能够详细点,先谢过了

------解决方案--------------------
ImageIcon imageIcon=new ImageIcon(this.getClass.getResource("ImageFileName"));
读取图片的时候你这样写试试...
我用的这个MyEclipes用你那个写法显示不出来图片,换成这样就行了...
------解决方案--------------------
我把代码给你改了一下。能够正常显示缩略图了。
package test;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.JPanel;

public class ImageViewer extends JPanel {
private static final long serialVersionUID = 7581047317531797244L;
private static Image srcImage;
private static int dstwidth = 0;
private static int dstheight = 0;

public ImageViewer(String ImageFileName) {
srcImage =Toolkit.getDefaultToolkit().getImage(this.getClass().getResource( ImageFileName));
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
int srcwidth = srcImage.getWidth(this);
int srcheight = srcImage.getHeight(this);
int maxsize = 100;
dstwidth = srcwidth;
dstheight = srcheight;
float k = 0;
if (srcwidth > maxsize) {
dstwidth = maxsize;
k = (float) srcwidth / (float) maxsize;
dstheight = Math.round((float) srcheight / k);
}
srcheight = dstheight;
if (srcheight > maxsize) {
dstheight = maxsize;
k = (float) srcheight / (float) maxsize;
dstwidth = Math.round((float) dstwidth / k);
}
if (srcImage != null) {
g.drawImage(srcImage,0,0,dstwidth, dstheight,null);
}

}

}