4

I'm working on a paint applet that draws different shapes. I want to draw lines while dragging the mouse. The problem is that when the lines appear, they are as shown in the image below.

enter image description here

I have class line that's constructed using one point (start point) and it has a method called setDragPoint that takes the mouse drag points in order to paint lines while dragging also the drawingImage makes too many flickers while drawing in dragging mode. Why does that happen?

import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

public class PaintBrush extends Applet implements MouseListener, MouseMotionListener {

Shape shape;
Point startPoint;
Point dragPoint;
ArrayList<Shape> shapes;
Choice shapeChoice;
Choice colorChoice;
Choice fillChoice;
Image drawingImage;
Graphics drawGraphics;
String shapeString, colorString, fillString;
boolean isDragMode;

public void init() {
    shapes = new ArrayList<Shape>();
    shapeChoice = new Choice();
    shapeChoice.addItem("Line");
    shapeChoice.addItem("Rectangle");
    shapeChoice.addItem("RoundRect");
    shapeChoice.addItem("Oval");
    shapeChoice.addItem("FreeHand");

    add(shapeChoice);

    colorChoice = new Choice();
    colorChoice.addItem("Red");
    colorChoice.addItem("Green");
    colorChoice.addItem("Blue");

    add(colorChoice);

    fillChoice = new Choice();
    fillChoice.addItem("Filled");
    fillChoice.addItem("Hollow");
    add(fillChoice);

    shapeString = shapeChoice.getSelectedItem();
    colorString = colorChoice.getSelectedItem();
    fillString = fillChoice.getSelectedItem();

    drawingImage = createImage(getSize().width, getSize().height);
    drawGraphics = drawingImage.getGraphics();
    System.out.println("set up image");
    drawGraphics.setColor(Color.black);
    drawGraphics.fillRect(0, 0, getSize().width, getSize().height);
    drawGraphics.setColor(Color.orange);
    drawGraphics.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
    drawGraphics.drawRect(1, 1, getSize().width - 3, getSize().height - 3);
    startPoint = new Point(0, 0);
    dragPoint = new Point(0, 0);
    addMouseListener(this);
    addMouseMotionListener(this);
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void mouseClicked(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {

    System.out.println("Pressed");

    startPoint.x = e.getX();
    startPoint.y = e.getY();
    repaint();

    switch (shapeString) {
        case "Line":
            shape = new Line(startPoint.x, startPoint.y);  //step 1 here i construct a new line using the start point (the point at which the mouse is pressed)

            break;
        case "FreeHand":
            shape = new FreeShape();
            break;
    }


    }

public void mouseReleased(MouseEvent e) {
    if (isDragMode) {
        shapes.add(shape);
        isDragMode = false;
     }
    repaint();

}

public void mouseMoved(MouseEvent e) {
}

public void mouseDragged(MouseEvent e) {
    System.out.println("Dragged");
    isDragMode = true;
    dragPoint.x = e.getX();
    dragPoint.y = e.getY();

    switch (shapeString) {
        case "Line":
            shape.setDragPoint(dragPoint.x, dragPoint.y);  //here i set the drag points to the already created line at step 1 
              break;
        case "FreeHand":
            shape = new FreeShape();
            break;
    }

    shape.drawWhileDragging(drawGraphics); // i call this method to draw while mouse is dragging

    repaint();


}

public void paint(Graphics g) {

  update(g);
}
 public void update(Graphics g) {

  // create an off-screen graphics drawing environment if none
  //existed
  // or if the user resized the applet drawing area to a different
 // size
   if (drawingImage == null)
{

System.out.println("Image is Null");
    drawingImage = createImage(getSize().width,getSize().height);
drawGraphics = drawingImage.getGraphics();
}



  // erase the previous image
  drawGraphics.setColor(Color.black);
  drawGraphics.fillRect(0,0,getSize().width,getSize().height);
  drawGraphics.setColor(Color.orange);
  drawGraphics.drawRect(0,0,getSize().width-1,getSize().height-1);
  drawGraphics.drawRect(1,1,getSize().width-3,getSize().height-3);  

   for(Shape s:shapes)
         s.draw(drawGraphics);

  // paint the offscreen image to the applet viewing window
  g.drawImage(drawingImage,0,0,this);

   }
 }


abstract class Shape {

Color shapeColor;
boolean filled;

abstract void draw(Graphics g);

void drawWhileDragging(Graphics g) {
}

void setDragPoint(int x, int y) {
}
}

 class Line extends Shape {

private Point startPoint;
private Point currentPoint;

public Point getStartPoint() {
    return startPoint;
}

public Point getCurrentPoint() {
    return currentPoint;
}

public void setStartPoint(Point point) {
    this.startPoint = point;
}

public void setCurrentPoint(Point point) {
    this.currentPoint = point;
}

void drawWhileDragging(Graphics g) {
    g.drawLine(startPoint.x, startPoint.y, currentPoint.x, currentPoint.y); 
}

public void draw(Graphics g) {
    g.drawLine(startPoint.x, startPoint.y, currentPoint.x, currentPoint.y);
}

Line() {
    startPoint = new Point(0, 0);
    currentPoint = new Point(0, 0);
}

Line(int x1, int y1) {
    this();
    this.startPoint.x = x1; 
    this.startPoint.y = y1;
}

void setDragPoint(int x, int y) {
    this.currentPoint.x = x;
    this.currentPoint.y = y;
    System.out.println("Current-X:" + currentPoint.x + " currentPoint-Y" + currentPoint.y);
    System.out.println("start-X:" + startPoint.x + " startPoint-Y" + startPoint.y);
  }

 }

class FreeShape extends Shape {

private ArrayList<Point> dragPoints = new ArrayList<Point>();

public ArrayList<Point> getDragPoints() {
    return dragPoints;
}

public void setDragPoints(Point point) {
    dragPoints.add(point);
}

public void draw(Graphics g) {
}

public FreeShape() {
  }
}


class Rectangle extends Shape {

public void draw(Graphics g) {
   }
 }


class Oval extends Shape {

public void draw(Graphics g) {
   }
 }
Eslam Hamdy
  • 7,126
  • 27
  • 105
  • 165

2 Answers2

1

I have written a similar type of app recently. Here is the screenshot. It is not fully developed as you can see.enter image description here

Now, I also faced similar problems as you are facing now. What you have to do is.

  • Double Buffer all painting operations
  • Do not clear the screen by calling repaint. Repaint actually first fills the screen with the background color & and that is the flicker you are seeing.

You can make a copy of the current screen canvas in an Image. The Image will be updated after every drawing operations. So Instead of clearing the screen by calling repaint what you do is draw the Image on the canvas. This is like double buffering.

In your code you are calling repaint every time the mouse is dragged. That is the cause of the flicker.


UPDATE

Three major issues I found in your newly updated code

  • In the drawWhileDragging Method you are not changing the line graphics context drawing color. So the line is actually drawn in black, and your background is black too. As a result you cannot see anything.
  • In this same method you are passing a graphics context (i.e. reference) of drawingImage. As a result the line is actually drawn on the offscreen image, not on the screen.
  • In mouseDragged method you are calling repaint after each drag. As a result nothing is actually painted

I have run your code on my machine and have made the necessary changes.I am posting only the changed methods to keep it short.

Here is the updated mouseDragged method

    public void mouseDragged(MouseEvent e) {
        System.out.println("Dragged");
        isDragMode = true;
        dragPoint.x = e.getX();
        dragPoint.y = e.getY();

        switch (shapeString) {
            case "Line":
                shape.setDragPoint(dragPoint.x, dragPoint.y);  //here i set the drag points to the already created line at step 1
                break;
            case "FreeHand":
                shape = new FreeShape();
                break;
        }

        getGraphics().drawImage(drawingImage, 0,0,null); //Added this line
        shape.drawWhileDragging(getGraphics()); // i call this method to draw while mouse is dragging
    }

Here is the updated drawWhileDragging method

    void drawWhileDragging(Graphics g) {
        g.setColor(Color.ORANGE);
        g.drawLine(startPoint.x, startPoint.y, currentPoint.x, currentPoint.y);
        g.setColor(Color.BLACK);
    }

Well, I have set the color to orange. What you have to do is to set the color according to the Choice menu.

You can implement a similar analogy for drawing other shapes as well.

Extreme Coders
  • 3,441
  • 2
  • 39
  • 55
  • @MadProgrammer The code originally posted used Applet instead of JApplet, that is why I suggested double buffering – Extreme Coders Dec 29 '12 at 07:19
  • @ExtremeCoders The problem is, the OP's attempting at double buffering is causing them problems - I agree with the concept, but I'm sure we can do better ;) – MadProgrammer Dec 29 '12 at 07:55
  • i updated my paint & update methods to let them erase the previous image and draw the new one, but this time the method drawWhileDragging has no effect at all at the image!! please see my updated methods – Eslam Hamdy Dec 29 '12 at 09:28
  • You can not rely in getGraphics returning a valid value. This will return the art graphics context used to paint the component and is,at best, a scratch pad. If repaint is called during before the paint is committed, it will be wiped clean – MadProgrammer Dec 29 '12 at 20:09
0

The issue you are having comes down to how you are "trying" to perform double buffering. Rather then clearing the backing buffer when you update the line position, you simple continuously painting to it - a little like drawing on a black board....

Instead, you need to clear the graphics content and reapply the updates - surprisingly, this is part of the what paint actually does, but you never call super.paint

There is rarely a need to override a top level container, nor should you rarely need to override the paint method of a top level container. Apart from everything else, there not double buffered.

Instead, use something like JPanel instead.

I've updated your example, excluding color. Color should actually be maintained by the shape and applied when it is painted.

public class BadPaint06 extends JApplet {

    public void init() {
        setLayout(new BorderLayout());
    }

    @Override
    public void start() {
        add(new PaintPane());
    }

    public class PaintPane extends JPanel implements MouseListener, MouseMotionListener {

        Shape shape;
        Point startPoint;
        Point dragPoint;
        ArrayList<Shape> shapes;
        Choice shapeChoice;
        Choice colorChoice;
        Choice fillChoice;
        Image drawingImage;
        Graphics drawGraphics;
        String shapeString, colorString, fillString;
        boolean isDragMode;

        public PaintPane() {
            shapes = new ArrayList<Shape>();
            shapeChoice = new Choice();
            shapeChoice.addItem("Line");
            shapeChoice.addItem("Rectangle");
            shapeChoice.addItem("RoundRect");
            shapeChoice.addItem("Oval");
            shapeChoice.addItem("FreeHand");

            add(shapeChoice);

            colorChoice = new Choice();
            colorChoice.addItem("Red");
            colorChoice.addItem("Green");
            colorChoice.addItem("Blue");

            add(colorChoice);

            fillChoice = new Choice();
            fillChoice.addItem("Filled");
            fillChoice.addItem("Hollow");
            add(fillChoice);

            shapeString = shapeChoice.getSelectedItem();
            colorString = colorChoice.getSelectedItem();
            fillString = fillChoice.getSelectedItem();

            startPoint = new Point(0, 0);
            dragPoint = new Point(0, 0);
            addMouseListener(this);
            addMouseMotionListener(this);
        }

        @Override
        public void invalidate() {

            drawingImage = null;

            super.invalidate(); 

        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mouseClicked(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {

            startPoint.x = e.getX();
            startPoint.y = e.getY();
            repaint();

            switch (shapeString) {
                case "Line":
                    shape = new Line(startPoint.x, startPoint.y);  //step 1 here i construct a new line using the start point (the point at which the mouse is pressed)

                    break;
                case "FreeHand":
                    shape = new FreeShape();
                    break;
            }


        }

        public void mouseReleased(MouseEvent e) {
            if (isDragMode) {
                shapes.add(shape);
                isDragMode = false;
            }
            repaint();

        }

        public void mouseMoved(MouseEvent e) {
        }

        public void mouseDragged(MouseEvent e) {
            System.out.println("Dragged");
            isDragMode = true;
            dragPoint.x = e.getX();
            dragPoint.y = e.getY();

            switch (shapeString) {
                case "Line":
                    shape.setDragPoint(dragPoint.x, dragPoint.y);  //here i set the drag points to the already created line at step 1 
                    break;
                case "FreeHand":
                    shape = new FreeShape();
                    break;
            }

            repaint();


        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            System.out.println("In Paint");
            if (drawingImage == null) {
                drawingImage = createImage(getSize().width, getSize().height);
                drawGraphics = drawingImage.getGraphics();
                System.out.println("set up image");
                drawGraphics.setColor(Color.black);
                drawGraphics.fillRect(0, 0, getSize().width, getSize().height);
                drawGraphics.setColor(Color.orange);
                drawGraphics.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
                drawGraphics.drawRect(1, 1, getSize().width - 3, getSize().height - 3);
                drawGraphics.dispose();
            }

            g.drawImage(drawingImage, 0, 0, this);

            for (Shape shape : shapes) {
                shape.draw(g);
            }


            if (shape != null) {
                shape.drawWhileDragging(g); // i call this method to draw while mouse is dragging
            }

        }
    }

    abstract class Shape {

        Color shapeColor;
        boolean filled;

        abstract void draw(Graphics g);

        void drawWhileDragging(Graphics g) {
        }

        void setDragPoint(int x, int y) {
        }
    }

    class Line extends Shape {

        private Point startPoint;
        private Point currentPoint;

        public Point getStartPoint() {
            return startPoint;
        }

        public Point getCurrentPoint() {
            return currentPoint;
        }

        public void setStartPoint(Point point) {
            this.startPoint = point;
        }

        public void setCurrentPoint(Point point) {
            this.currentPoint = point;
        }

        void drawWhileDragging(Graphics g) {
            if (currentPoint != null) {
                g.drawLine(startPoint.x, startPoint.y, currentPoint.x, currentPoint.y);
            }
        }

        public void draw(Graphics g) {
            if (currentPoint != null) {
                g.drawLine(startPoint.x, startPoint.y, currentPoint.x, currentPoint.y);
            }
        }

        Line() {
            startPoint = new Point(0, 0);
//            currentPoint = new Point(0, 0);
        }

        Line(int x1, int y1) {
            this();
            this.startPoint.x = x1;
            this.startPoint.y = y1;
        }

        void setDragPoint(int x, int y) {
            currentPoint = new Point(x, y);
//            this.currentPoint.x = x;
//            this.currentPoint.y = y;
            System.out.println("Current-X:" + currentPoint.x + " currentPoint-Y" + currentPoint.y);
            System.out.println("start-X:" + startPoint.x + " startPoint-Y" + startPoint.y);
        }
    }

    class FreeShape extends Shape {

        private ArrayList<Point> dragPoints = new ArrayList<Point>();

        public ArrayList<Point> getDragPoints() {
            return dragPoints;
        }

        public void setDragPoints(Point point) {
            dragPoints.add(point);
        }

        public void draw(Graphics g) {
        }

        public FreeShape() {
        }
    }

    class Rectangle extends Shape {

        public void draw(Graphics g) {
        }
    }

    class Oval extends Shape {

        public void draw(Graphics g) {
        }
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • i updated my paint & update methods to let them erase the previous image and draw the new one, but this time the method drawWhileDragging has no effect at all at the image!! please see my updated methods – Eslam Hamdy Dec 29 '12 at 09:29
  • @Eslam Your `drawWhileDragging` and `draw` methods are the same, I'm not sure what difference they are suppose to be have – MadProgrammer Dec 29 '12 at 11:56
  • the draw method is called only after the mouse is released, so i make the method drawWhileDragging to draw while the mouse is dragging, i tested it and it's called but the image is not updated, but the flicker is removed due to my last update – Eslam Hamdy Dec 29 '12 at 14:34
  • @ExtremeCoders JPanel (actually all Swing components) implement ImageObserver, this way, the component will take care of the repaints as required – MadProgrammer Dec 29 '12 at 20:06