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.
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
Two possible solutions:
getGraphics()
, and then draw the BufferedImage in your JPanel's paintComponent(Graphics g)
method. OrArrayList<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:
paintComponent(Graphics g)
method.paintComponent(Graphics g)
method override.