JFrame 重画 拖影解决方案

来源:互联网 发布:java. object类 编辑:程序博客网 时间:2024/04/29 11:24

看到好多人反应,使用JFrame重画时,会有残留上一帧的图案。

也有好多童鞋想要擦除图上的某一条线,对于这个问题有人提出“画一条与底色相同的线将原来的线覆盖掉就好了”。其实这样是有致命缺点的,比如:底色是图案或者两线相交时。

之所以出现这些问题其实是对重画的理解偏差,而不在于技术。所谓重画,就是用一张新图覆盖掉上一帧老图,而不是改变上一帧老图。

说这么多其实解决起来很简单,把包括底色在内的所有东西(不包括你想要删除的内容 /坏笑)重新画一遍就好了,见代码:


import com.sun.awt.AWTUtilities;import javax.imageio.ImageIO;import javax.swing.*;import java.awt.*;import java.awt.image.BufferedImage;import java.io.IOException;/** * Created by zhaohebing on 2017-03-07. */public class Gift extends JPanel {    private static BufferedImage[] images;    static{        try {            images = new BufferedImage[2];            images[1] = ImageIO.read(Gift.class.getResource("IMG00001.png"));            images[0] = ImageIO.read(Gift.class.getResource("IMG00000.png"));        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    int index = 0,i = 0;    @Override    public void paint(Graphics g){
    if (index++%200==0) {        //重画背景        g.drawImage(images[i++%2], 0, 0, null);        //重新显示文字        g.drawString("第"+i+"次重画",images[0].getWidth()/2,images[0].getHeight()/2);    }
        repaint();//画完重画    }    public static void main(String[] args) {        JFrame frame = new JFrame("恶心不?恶心别从这儿关啊");        Gift b = new Gift();        frame.add(b);        frame.setSize(images[0].getWidth(),images[0].getHeight());        frame.setAlwaysOnTop(true);        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置了没有关闭按钮        frame.setLocationRelativeTo(null); // 设置窗体初始位置        frame.setUndecorated(true);        AWTUtilities.setWindowOpaque(frame, false);        frame.setVisible(true); // 尽快调用paint
try {            Thread.sleep(1000*8);//等待8秒        } catch (InterruptedException e) {            e.printStackTrace();        }        frame.dispose();//关闭    }}
重点在 paint(Graphics g) 方法中,如果不重画背景,在显示次数时,数字会发生重叠,把1,2,3,4,5...一堆数字重叠显示在一起,最终形成一个大疙瘩。

1 0
原创粉丝点击