Repaint Applets in JAVA without losing previous contents

前端 未结 2 1318
执念已碎
执念已碎 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<Point> points = new ArrayList<Point>();
    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
    
    0 讨论(0)
  • 2021-01-15 10:00

    Two possible solutions:

    1. Draw to a BufferedImage using the Graphics object obtained from it via getGraphics(), and then draw the BufferedImage in your JPanel's paintComponent(Graphics g) method. Or
    2. Create an ArrayList<Point> place your mouse points into the List, and then in the JPanel's paintComponent(Graphics g) method, iterate through the List with a for loop, drawing all the points, or sometimes better -- lines that connect the contiguous points.

    Other important suggestions:

    • Be sure that you're using the Swing library (JApplet, JPanel), not AWT (Applet, Panel, Canvas).
    • You're better off avoiding applets if at all possible.
    • Don't draw in a paint method but rather a JPanel's paintComponent(Graphics g) method.
    • Don't forget to call the super's method first thing in your paintComponent(Graphics g) method override.
    0 讨论(0)
提交回复
热议问题