public class ImgPanel extends JPanel{
private Image _img=null;
private int _imgWidth,_imgHeight; // 初始图片的长宽
public ImgPanel() {
}
public void setImage(Image image){
_img=image;
repaint();
}
public void paintComponent(Graphics g){
if(_img!=null){
_imgWidth=_img.getWidth(this); // 没有得到值,只返回了一个-1
_imgHeight=_img.getHeight(this); // 得到值了
g.drawImage(_img,0,0,_imgWidth,_imgHeight,this);
}
}
}我用跟踪发现Image.getWidth(this)得到-1,而Image.getHeight(this)却能得到正确值.
by the way:图片是用这个方法得到的
Image img=Toolkit.getDefaultToolkit().createImage("C:\\1.JPG"); 然后传到这个ImgPanel中去的。
private Image _img=null;
private int _imgWidth,_imgHeight; // 初始图片的长宽
public ImgPanel() {
}
public void setImage(Image image){
_img=image;
repaint();
}
public void paintComponent(Graphics g){
if(_img!=null){
_imgWidth=_img.getWidth(this); // 没有得到值,只返回了一个-1
_imgHeight=_img.getHeight(this); // 得到值了
g.drawImage(_img,0,0,_imgWidth,_imgHeight,this);
}
}
}我用跟踪发现Image.getWidth(this)得到-1,而Image.getHeight(this)却能得到正确值.
by the way:图片是用这个方法得到的
Image img=Toolkit.getDefaultToolkit().createImage("C:\\1.JPG"); 然后传到这个ImgPanel中去的。
Image image = Toolkit.getDefaultToolkit().getImage(imageName);
//the following line is important,
//it is ensuring the pixels of the image are loaded
image = new ImageIcon(image).getImage();