swing项目解决JPane绘制图片残留问题

1 篇文章 0 订阅

1.问题

在写一个放大缩小图片的小应用,我发现在缩小后,会有原来的图片残留。

下面是我继承jpanel类绘制的图片

因为我担心内存溢出问题,所以重写了绘制的方法

public class ZPanel extends javax.swing.JPanel {

    private static final long serialVersionUID = 1L;
    private Image image;

    private Image copyImage;
    private int imgWidth;
    private int imgHeight;

    public Image getCopyImage() {
        return copyImage;
    }

    public int getImgWidth() {
        return imgWidth;
    }

    public void setImgWidth(int imgWidth) {
        this.imgWidth = imgWidth;
    }

    public int getImgHeight() {
        return imgHeight;
    }

    public Image getImage() {
        return image;
    }

    public void setImgHeight(int imgHeight) {
        this.imgHeight = imgHeight;
    }

    public ZPanel() {
    }

    public void setImagePath(String imgPath) {

        try {
            // 该方法会将图像加载到内存,从而拿到图像的详细信息。
            image = ImageIO.read(new FileInputStream(imgPath));
            if (copyImage == null){
                copyImage = ImageIO.read(new FileInputStream(imgPath));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        setImgWidth(image.getWidth(this));
        setImgHeight(image.getHeight(this));
    }
    public void setImage(BufferedImage bufferedImage) {

        image = bufferedImage;
        setImgWidth(image.getWidth(this));
        setImgHeight(image.getHeight(this));
    }


    @Override
    public void paintComponent(Graphics g1) {

        int x = 0;
        int y = 0;
        Graphics g = (Graphics) g1;
        if (null == image) {
            return;
        }
        g.drawImage(image, x, y, image.getWidth(this), image.getHeight(this),
                this);
        g = null;

    }
}

因为这是直接画在画板上的,所以,removeAll(),等清除组件的方法通通没用

下面是残留的效果

在这里插入图片描述





2.尝试解决

果然是java快淘汰的玩意,许多博客都停留在起码7年前,很多都是10年前的,当初c站的实力毋容置疑
在这里插入图片描述

Graphics g; //画板很容易拿到
g.clearRect(0,0,4000,4000);

通过使用当前绘图表面的背景色进行填充来清除指定的矩形

实际上jpael是类似画图的工具,既然有画笔自然有橡皮,这个方法相当于是橡皮的作用,对改区域进行背景色填充,实现消除画板图片

 public void paintComponent(Graphics g1) {

        int x = 0;
        int y = 0;
        Graphics g = (Graphics) g1;
        if (null == image) {
            return;
        }
        g.clearRect(0,0,4000,4000);
        g.drawImage(image, x, y, image.getWidth(this), image.getHeight(this),
                this);
        g = null;

    }



3.成功解决!! 😊😊😊😊😊😊

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

只会写bug的靓仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值