Repaint Applets in JAVA without losing previous contents

前端 未结 2 1342
执念已碎
执念已碎 2021-01-15 09:18

Is it possible to re-paint an applet without losing its previous contents? I was just trying to make a program which allows users to draw lines, Rectangle etc. using mouse.

2条回答
  •  悲哀的现实
    2021-01-15 09:44

    You need to keep track of everything that has been painted and then repaint everything again.

    See Custom Painting Approaches for the two common ways to do this:

    Use a ArrayList to keep track of objects painted Use a BufferedImage

    here is an exemple of code you can use :

    ArrayList points = new ArrayList();
    private void draw(Graphics g){
        for (Point p: this.points){
                g.fillOval(1, 2, 2, 2);
        }
    }
    
    //after defining this function you add this to your paint function :
    draw(g)
    g.drawRect(x1, y1, x2-x1, y2-y1);
    points.add(new Point(x1, y1, x2-x1, y2-y1))
    // PS : point is a class I created to refer to a point, but you can use whatever
    

提交回复
热议问题