在Java中将图像加载到背景中 [英] Loading an image into a background in java

查看:91
本文介绍了在Java中将图像加载到背景中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中将图像加载到背景中?我尝试了许多不同的方法,但没有一个起作用,所以我问是否有人知道如何将png图像上传到jpannel中

How do you load an image into a background in Java? I have tried many different methods and none of them work so I am asking if anyone knows how to upload a png image into a jpannel

推荐答案

制作自己的JPanel.在GUI的构造函数中添加PicPanel对象.

Make your own JPanel. Add an object of PicPanel in your GUI's constructor.

class PicPanel extends JPanel{

    private BufferedImage image;
    private int w,h;
    public PicPanel(String fname){ //Pass picture's filename as a parameter.

        //reads the image
        try {
            image = ImageIO.read(getClass().getResource("/"+fname));
            w = image.getWidth();
            h = image.getHeight();

        } catch (IOException ioe) {
            System.out.println("Could not read in the pic");
            //System.exit(0);
        }

    }

    public Dimension getPreferredSize() {
        return new Dimension(w,h);
    }
    //this will draw the image
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(image,0,0,this);
    }
}

这篇关于在Java中将图像加载到背景中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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