如何将图像添加到 JPanel? [英] How to add an image to a JPanel?

查看:42
本文介绍了如何将图像添加到 JPanel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JPanel to which I'd like to add JPEG and PNG images that I generate on the fly.

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

All the examples I've seen so far in the Swing Tutorials, specially in the Swing examples use ImageIcons.

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

I'm generating these images as byte arrays, and they are usually larger than the common icon they use in the examples, at 640x480.

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

编辑:对教程和 API 的更仔细检查表明您不能将 ImageIcon 直接添加到 JPanel.相反,它们通过将图像设置为 JLabel 的图标来实现相同的效果.这只是感觉不对...

Edit: A more careful examination of the tutorials and the API shows that you cannot add an ImageIcon directly to a JPanel. Instead, they achieve the same effect by setting the image as an icon of a JLabel. This just doesn't feel right...

推荐答案

这是我的做法(关于如何加载图像的更多信息):

Here's how I do it (with a little more info on how to load an image):

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            
    }

}

这篇关于如何将图像添加到 JPanel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆