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();
    }

    Triangle()
    {
        addMouseListener(mouseListener);
        addMouseMotionListener(mouseMotionListener);

        this.setSize(600, 500);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

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

        @Override
        public void mouseReleased(MouseEvent e) {

            if (startDrag.x > endDrag.x)
                midPoint = new Point((endDrag.x +(Math.abs(startDrag.x - endDrag.x)/2)),e.getY());
            else
                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;
            repaint();
        }

    };

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

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

        }
    };

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

        for (Polygon triangle : triangles)
            g2.fillPolygon(triangle);
    }
}

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 ?
Thanks

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 ! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.