[英]How do I make the circle bigger than the arcs inside without going off center?
這是我的代碼:
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class fourfans extends JFrame {
public fourfans(){
setTitle("DrawArcs");
add(new ArcsPanel());
add(new ArcsPanel());
add(new ArcsPanel());
add(new ArcsPanel());
}
public static void main(String[] args) {
fourfans frame = new fourfans();
GridLayout test = new GridLayout(2,2);
frame.setLayout(test);
frame.setSize(250 , 300);
frame.setLocationRelativeTo(null); // center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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.drawOval(x, y, 2 * radius, 2 * radius);
}
}
每次我嘗試將2 *半徑更改為2.1 *半徑時,它都不會讓我接受,因為那是兩倍。 然后,當我輸入一個大於圓弧的固定數字時,它會使圓偏心。
之所以要輸入比圓弧大的數字,是因為圓偏離中心,是因為Java將左上角的x,y插入,而不是圓/圓弧的原點。 因此,如果您將其中一個增大,則必須重新計算其x和y的值,例如
int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);
int radiusOval = (int)(Math.min(getWidth(), getHeight()) * 0.4 * 1.05);
int x = xCenter - radius;
int y = yCenter - radius;
int xOval = xCenter - radiusOval;
int yOval = yCenter - radiusOval;
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.drawOval(xOval, yOval, (int)(2.1 * radius), (int)(2.1 * radius));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.