效果
代码:
package Test;
import javax.swing.*;
import java.awt.*;
public class TestFrame extends JFrame {
public TestFrame(){
setTitle("DrawArcs");
add(new ArcsPanel());
}
public static void main(String[] args) {
TestFrame frame=new TestFrame();
frame.setTitle("TestFigurePanel");
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ArcsPanel extends JPanel{
protected void paintComponent(Graphics g){
super.paintComponent(g);
int xCenter=getWidth()/2;
int yCenter=getHeight()/2;
int radius=(int)(Math.min(getWidth(),getHeight()*0.4));
int x=xCenter-radius;
int y=yCenter-radius;
g.fillArc(x,y,2*radius,2*radius,0,30);
g.fillArc(x,y,2*radius,2*radius,90,30);
g.fillArc(x,y,2*radius,2*radius,180,30);
g.fillArc(x,y,2*radius,2*radius,270,30);
}
}
讲解
g.fillArc(x,y,2*radius,2*radius,0,30);
就是从(x,y)作为起点,长度和高度是2*radius,从0°开始绘制,到30°结束。其余三个都是以此类推。
因为选择的是fill,所以是实心的,默认为黑色。
角度也可以为负数,从东边开始,逆时针为正数。