Repaint Applets in JAVA without losing previous contents

前端 未结 2 1319
执念已碎
执念已碎 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 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 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.

提交回复
热议问题