import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.GeneralPath;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ArcPie extends JPanel {
public ArcPie() {
setPreferredSize(new Dimension(200, 200));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final Rectangle rect = getBounds();
final Area pie = createArcPie(rect.x, rect.y, Math.min(rect.width, rect.height), 10, 40, .3);
((Graphics2D) g).draw(pie);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ArcPie());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
/**
* Constructs a new arc, initialized to the specified location, size, angular extents, and percentage.
*
* @param x
* The X coordinate of the upper-left corner of the arc's framing rectangle.
* @param y
* The Y coordinate of the upper-left corner of the arc's framing rectangle.
* @param d
* The overall diameter of the full ellipse of which this arc is a partial section.
* @param start
* The starting angle of the arc in degrees.
* @param extent
* The angular extent of the arc in degrees.
* @param p
* How much of the arc to be cut in percent.
*/
public static Area createArcPie(double x, double y, double d, double start, double extent, double p) {
final Area pie = new Area(new Arc2D.Double(x, y, d, d, start, extent, Arc2D.PIE));
final double centerX = (x + d) / 2;
final double centerY = (y + d) / 2;
final double alpha = -Math.toRadians(start - 1); // Wegen Ungenauigkeit bei double den Startwinkel verkleinern ...
final double beta = alpha + -Math.toRadians(extent + 2); // und den Endwinkel vergrößern.
final double cosA = Math.cos(alpha);
final double cosB = Math.cos(beta);
final double sinA = Math.sin(alpha);
final double sinB = Math.sin(beta);
final double r = p * d / 2;
final GeneralPath gp = new GeneralPath();
gp.moveTo(centerX, centerY);
gp.lineTo(r * cosA + centerX, r * sinA + centerY);
gp.lineTo(r * cosB + centerX, r * sinB + centerY);
gp.closePath();
pie.subtract(new Area(gp));
return new Area(pie);
}
}