Search code examples
javarotationawtgraphics2dpie-chart

How can I rotate pie chart in java


I have code to draw a pie chart with value and random colors. Now I would like to rotate the entire figure, not one piece of pie. Here is my code:

class Slice{

    double value;
    Color color;
    public Slice(double _value){
        this.value = _value;    
    }
    public void setColor(Color _color){
        this.color = _color;

    }
}

class Component extends JComponent implements MouseListener{

    int movx = 0;
    int movy = 0;

    Slice[] slice = {new Slice(5),new Slice(20),new Slice(33),new Slice(55)};
    public Component(){
        addMouseListener(this);
    }

    public void paint(Graphics g){
        Graphics2D g2 = (Graphics2D)g;
        drawPie(g2, getBounds(), slice);

    }
    public void drawPie(Graphics2D g, Rectangle area, Slice[] s){
        double total = 0.0D;
        //calculate total value
        for(int i=0;i<s.length;i++)
            total+=s[i].value;

        double curentValue = 0.0D;
        int startAngle = 0;
        for(int i = 0;i<s.length;i++){
            Random numGen = new Random();
            s[i].setColor(new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256)));
            startAngle = (int)((curentValue*360)/total);
            int arcAngle = (int)((s[i].value*360)/total) ;
            g.setColor(s[i].color);
            g.rotate(30);//row AA
            g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);   

            curentValue+=s[i].value;

        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        movx = e.getX();
        movy = e.getY();
        repaint();
    }

    // unimplemented Mouse methods removed
}

public class PieChart {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame();
        frame.getContentPane().add(new Component());
        frame.setSize(300,200);
        frame.setVisible(true);
    }
}

In row AA when I write rotate, it cannot work normally? Can you help me? How can I rotate the entire chart?


Solution

  • The argument of Graphics2D.rotate is in radians.

    http://docs.oracle.com/javase/6/docs/api/java/awt/Graphics2D.html#rotate%28double%29

    http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees

    If you want to rotate the whole chart, you should put the rotate code at the beginning of the drawPie method, not in the for loop.