我想旋转关于他的中心的饼图,我该怎么做?我想旋转整个饼图。这是我的代码:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
class Slice{
double value;
Color color;
public Slice(double _value){
Random numGen = new Random();
int R = numGen.nextInt(256);
int G = numGen.nextInt(256);
int B = numGen.nextInt(256);
this.setColor(new Color(R,G,B));
this.value = _value;
}
public void setColor(Color _color){
this.color = _color;
}
}
class Component extends JComponent {
int movx = 0;
int movy = 0;
private double angle = 0;
private double radius = 0.0D;
private Random numGen;
private int w = 500;
private int h = 500;
Slice[] slice = {new Slice(5),new Slice(20),new Slice(33),new Slice(42)};
public Component(){
numGen = new Random();
Listener listener = new Listener();
addMouseListener(listener);
addMouseMotionListener(listener);
}
class Listener extends MouseAdapter{
private double LastAngle;
@Override
public void mousePressed(MouseEvent e) {
LastAngle = getAngle(e.getPoint());
}
@Override
public void mouseDragged(MouseEvent e) {
double curAngle = getAngle(e.getPoint());
double deltaAngle = curAngle - LastAngle;
angle += deltaAngle;
repaint();
LastAngle = curAngle;
}
private double getAngle(Point point) {
double x = point.getX() - 0.5 * 500;
double y = point.getY() - 0.5 * 500;
return Math.atan2(y, x);
}
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
//g2.translate(250, 250);
g2.rotate(angle,w/2-5,h/2-5);
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;
radius = total/2*Math.PI;
double curentValue = 0.0D;
int startAngle = 0;
for(int i = 0;i<s.length;i++){
//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(angle);//row AA
for(int j=1;j>0;j--){
g.fillArc(j, j, w, h, startAngle, arcAngle);
}
curentValue+=s[i].value;
}
}
}
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(600,600);
frame.setVisible(true);
}
}
我该怎么做?我写w / 2,h / 2,因为在fillArc中我写宽度和500,但它不围绕中心旋转。
答案 0 :(得分:3)
您正在使用
g2.rotate(angle,w/2-5,h/2-5);
将旋转饼图关于偏心点。你可以使用:
g2.rotate(angle, (w / 2) + 1, (h / 2) + 1);
答案 1 :(得分:1)
作为使用JFreeChart
的替代方案,请在封闭式ChartPanel
上调用setMouseWheelEnabled()
以启用轮播,如PieChartDemo1
source所示。