2

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. I have used the repaint method but it does not keep the previously drawn lines/rectangles etc.

Here is the snippet:

public void mousePressed(MouseEvent e){x1=e.getX();y1=e.getY();}
public void mouseDragged(MouseEvent e)
{
    x2=e.getX();
    y2=e.getY();
    repaint();
    showStatus("Start Point: "+x1+", "+y1+"         End Point: "+x2+", "+y2);
}
public void paint(Graphics g)
{
    //g.drawLine(x1,y1,x2,y2);
    g.drawRect(x1, y1, x2-x1, y2-y1);

}
ManJoey
  • 213
  • 2
  • 7
  • use clipping to repaint only specific part of the UI. – Braj May 28 '14 at 03:36
  • 2
    @Braj Clippings kind of dangerous as you could end up painting out side of the "visible" bounds of the component onto other parts of the screen...looks really cool actually, but this is why I avoid it - just saying... – MadProgrammer May 28 '14 at 03:41

2 Answers2

2

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.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    +1, See [Custom Painting Approaches](http://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/) for working examples of both of the suggested approaches. Each example allows the user to draw Rectangles of a different Color. – camickr May 28 '14 at 03:45
1

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
FrankelStein
  • 907
  • 2
  • 13
  • 30