0

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);
    }
}
2
Contributors
4
Replies
21
Views
1 Month
Discussion Span
Last Post by RAHEEL_3
1

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.

1

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?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.