Mushahid Hussain
Mushahid Hussain

Reputation: 4055

Calculating Arc Angle In Java

when i right click on the the Jframe this pie appears. what i want is to calculate the angle of each pie when click event occurs.

 Color[] c = {Color.BLACK, Color.RED, Color.BLUE, Color.YELLOW, 
                     Color.GREEN, Color.CYAN, Color.MAGENTA, Color.PINK};
        for(int i=0; i<8; ++i){
            g.setColor(c[i]);
            g.fillArc(x, y, w, h, i*45, 45);
        }

here what i have tried

  public void mouseClicked(MouseEvent e) 
        {


              PointerInfo a = MouseInfo.getPointerInfo();
               Point d  = a.getLocation();
               x1 = (int)d.getX();
               y1 = (int)d.getY();
               int base=x1-CenterX;
               int prep=CenterY-y1;
               double tan=prep/base;
               double angle=Math.atan( tan);
  }

but the calculted angle is not correct. it some times give me divide by zero exception. and here is my right click event which shows the menu.

  public void mousePressed(MouseEvent e) {
            if(e.isPopupTrigger())
            {
                CenterX=e.getX();
                CenterY=e.getY();
              try {
                    Thread.sleep(300L);
                } catch (InterruptedException ex) {
                    Logger.getLogger(animate.class.getName()).log(Level.SEVERE, null, ex);
                }
        p.repaint();
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if(e.isPopupTrigger()){
               s=e.getX();
                as=e.getY();
                p.mx=e.getX(); 
        p.my=e.getY();

Upvotes: 0

Views: 842

Answers (1)

Michael Slade
Michael Slade

Reputation: 13877

Yes, a divide by zero will happen if base == 0, ie if x1 == CenterX.

use Math.atan2. It converts x/y coordinates to angles and takes care of all of the messy math for you.

Upvotes: 1

Related Questions