Hi there,

I want to draw a triangle using mouse events like mousePressed(), mouseReleased() and mouseDragged(). But triangle did not show until mouse release. Please tell me what i am doing wrong that triangle is not showing in mouseDrag event.

And one thing more, triangle is drawing upside down. Please tell me how to fix it.
Thank you !

public class Triangle extends JFrame {

    Point startDrag, endDrag, midPoint;
    private java.util.List<Polygon> triangles = new LinkedList<Polygon>();

    public static void main(String[] args)
        Triangle t = new Triangle();


        this.setSize(600, 500);

    MouseListener mouseListener = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            startDrag = new Point(e.getX(), e.getY());
            endDrag = startDrag;

        public void mouseReleased(MouseEvent e) {

            if (startDrag.x > endDrag.x)
                midPoint = new Point((endDrag.x +(Math.abs(startDrag.x - endDrag.x)/2)),e.getY());
                midPoint = new Point((endDrag.x -(Math.abs(startDrag.x - endDrag.x)/2)),e.getY());

            int[] xs = { startDrag.x, endDrag.x, midPoint.x };
            int[] ys = { startDrag.y, startDrag.y, midPoint.y };

            triangles.add( new Polygon(xs, ys, 3));

            startDrag = null;
            endDrag = null;


    MouseMotionListener mouseMotionListener = new MouseMotionAdapter() {
        public void mouseDragged(MouseEvent e) {

            endDrag = new Point(e.getX(), e.getY());


    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        for (Polygon triangle : triangles)

That's because you don't add the new triangle to triangles until the mouse is released.

Upside down may be because y coordinates start at 0 at the top and increase downwards.

What changes do i made to fix this issue ?

You need to create your triangle on mousePressed, and keep updating it as the mouse is moved.

ps: down voter: did I get something wrong?

Problem solved. Thank you JamesCherrill ! :)