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

查看:132
本文介绍了如何将图像添加到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 Tutorials ,特别是在 Swing示例使用 ImageIcon s。

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?

  1. Is there any (performance or other) problem in using the ImageIcon class to display an image that size in a JPanel?
  2. What's the usual way of doing it?
  3. How to add an image to a JPanel without using the ImageIcon class?

编辑:仔细检查教程和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天全站免登陆