Skip to main content

Calculate polygon area. Pls HELP!

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
No replies
ded0mraz
Offline
Joined: 2013-08-16

i have this program for drawing polygon and now i'm trying to implement a function to calculate the area of the polygon. i tried but i am still a beginner i programming, so i appreciate any help. here is the code:

import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.Polygon;

public class DrawPolygons extends JApplet implements ActionListener, MouseListener
{
private static final int NUMPOINTS =

private JButton finish;
private Polygon shape;
private boolean isDrawn;
private int count;
private Color color;
private int[] x;
private int[] y;
private float sum;
private double area;

public void init()
{
setLayout(new FlowLayout());

addMouseListener(this);

isDrawn = false;
count = 0;
x = new int[NUMPOINTS];
y = new int[NUMPOINTS];

finish = new JButton("Finalize points");
finish.addActionListener(this);
add(finish);

color = Color.BLACK;

shape = new Polygon();

}

public void paint(Graphics g)
{
super.paint(g);

g.drawPolyline(x, y, count);

g.setColor(color);

if(isDrawn)
{

g.fillPolygon(x, y, count);

}
}

public void actionPerformed(ActionEvent a)
{
if(a.getSource() == finish)
{
isDrawn = true;

color = Color.red;

repaint();

JOptionPane.showMessageDialog(null, "The area is " + sum);
}
}

public void mouseClicked(MouseEvent e)
{

if(isDrawn == false && count < NUMPOINTS)
{
x[count] = e.getX();
y[count] = e.getY();
count++;
repaint();

}

else if (e.isShiftDown()) {

count = 0;
isDrawn = false;
repaint();
}

}

//the function!!!

private float getPolygonArea(int[] x, int[] y, int count)
{
float sum_but_no_result=0;

for(int i=0;i<(count-1);i++) // count is point number of polygon
{
sum_but_no_result+=x[i]*y[i+1] + y[i]*x[i+1];
}
sum_but_no_result+=x[count-1]*y[0] + y[count-1]*x[0];

float sum = (float)Math.abs(sum_but_no_result) / 2.0f;
return sum;
}

public void mousePressed(MouseEvent e){};
public void mouseReleased(MouseEvent e){};
public void mouseEntered(MouseEvent e){};
public void mouseExited(MouseEvent e){};

}