views:

269

answers:

2

I was wondering how to fill in a triangle shape with color when a user click on the triangle.

So far I am using txt file as input file to read the coordinate of the triangle to be drawn on screen.

+1  A: 

I did something like this long ago .. here's something that might help

Aziz
A: 

Not sure what your "environment is"...

Extend a JPanel.
Add an MouseAdapter to capture the coordinates in the mouseClicked method and save them in an array in your panel.
Override the drawComponent method to draw the triangle. Something like

class MyPanel extends JPanel {
    private int count = 0;
    private Point[] points = new Point[3];

    MyPanel() {
        setBackground(Color.WHITE);
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    if (count == points.length) {
                        for (int i = 1; i < points.length; i++) {
                            points[i-1] = points[i];
                        }
                        count -= 1;
                    }
                    points[count] = e.getPoint();
                    count += 1;
                    repaint();
                }
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D gg = (Graphics2D) g;
        if (count > 2) {
            Polygon polygon = new Polygon();
            for (int i = 0; i < count; i++) {
                polygon.addPoint(points[i].x, points[i].y);
            }
            gg.setColor(Color.BLUE);
            gg.fill(polygon);
        }
    }
}

It's not complete, but ...

Carlos Heuberger