java JPanel 和 BufferedImage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15796425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPanel and BufferedImage
提问by MQSJ23
How do you display a BufferedImage in a JPanel ?
如何在 JPanel 中显示 BufferedImage ?
回答by Alya'a Gamal
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File("image name and path"));
} catch (IOException ex) {
// handle exception...
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
and try to read this Example to display BufferedImage as ImageIcon
回答by That Homeless Guy
I'm not sure right now but I believe you need to do an
我现在不确定,但我相信你需要做一个
BufferedImage image = ImageIO.read(new File("image path"));
ImageIcon img = new ImageIcon(image);
img.setVisible(true);
add(img);
inside the constructor.
I cant remember right now and I dont have the compiler to hand to test but thats how I add images to the panel normaly and the just call super.repaint();
as needed.
在构造函数里面。我现在不记得了,我没有编译器来测试,但这就是我如何将图像正常添加到面板并super.repaint();
根据需要调用。
Edit: I believerepaint();
will do the job too.
编辑:我相信repaint();
也会完成这项工作。