小编典典

Java如何将图像添加到JPanel?

java

我有一个JPanel,我想向其中添加即时生成的JPEG和PNG图像。

到目前为止,我在Swing教程中看到的所有示例,特别是在Swing示例中,都使用ImageIcon。

我将这些图像生成为字节数组,它们通常比示例中使用的通用图标大,尺寸为640x480。

  1. 使用ImageIcon类在JPanel中显示该大小的图像时是否存在任何(性能或其他)问题?
  2. 什么是平常做的呢?
  3. 如何不使用ImageIcon类将图像添加到JPanel?

编辑:对教程和API的更仔细的检查表明,你不能将ImageIcon直接添加到JPanel。而是通过将图像设置为JLabel的图标来达到相同的效果。只是感觉不对…


阅读 1351

收藏
2020-02-26

共1个答案

小编典典

这是我的操作方法(有关如何加载图像的更多信息):

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, this); // see javadoc for more info on the parameters            
    }

}
2020-02-26