【发布时间】:2012-03-09 12:58:09
【问题描述】:
我想在中心的边框布局面板中显示图像。 我如下创建图像面板,然后将其添加到边框布局的中心。 我不知道为什么图像不显示,也没有错误。 可能是什么原因,我该如何解决?
public class ImagePanel extends WebPanel {
private Image image;
private Image scaledImage;
private int imageWidth = 0;
private int imageHeight = 0;
//constructor
public ImagePanel() {
super();
}
public void loadImage(String file) throws IOException {
File filetest= new File("C:\\tmp\\axiuser\\Pictures\\CLA0014.png");
image = ImageIO.read(filetest);//new File(file)
imageWidth = image.getWidth(this);
imageHeight = image.getHeight(this);
setScaledImage();
}
//e.g., containing frame might call this from formComponentResized
public void scaleImage() {
setScaledImage();
}
//override paintComponent
public void paintComponent(Graphics g) {
super.paintComponent(g);
if ( scaledImage != null ) {
//System.out.println("ImagePanel paintComponent " + ++paintCount);
g.drawImage(scaledImage, 0, 0, this);
}
}
private void setScaledImage() {
if ( image != null ) {
//use floats so division below won't round
float iw = imageWidth;
float ih = imageHeight;
float pw = this.getWidth(); //panel width
float ph = this.getHeight(); //panel height
if ( pw < iw || ph < ih ) {
if ( (pw / ph) > (iw / ih) ) {
iw = -1;
ih = ph;
} else {
iw = pw;
ih = -1;
}
//prevent errors if panel is 0 wide or high
if (iw == 0) {
iw = -1;
}
if (ih == 0) {
ih = -1;
}
scaledImage = image.getScaledInstance(
new Float(iw).intValue(), new Float(ih).intValue(), Image.SCALE_DEFAULT);
} else {
scaledImage = image;
}
}
}
}
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖SSCCE。
-
在下面查看我的答案,用 JPEG 文件尝试一下,看看它是否有效。
-
你的 ImagePanel 的尺寸是多少?如果您使用的是布局管理器,您还应该将 ImagePanel 的 preferredSize 设置为您的 scaledImage 的大小,否则,ImagePanel 的大小将为 0x0,您将永远看不到您的图像。