简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM