2013-03-26 58 views
0

這是我的代碼:如何在不偏離中心的情況下使圓形比圓弧更大?

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 *半徑,它不會讓我,因爲這是一個雙。然後當我輸入一個大於弧線的固定數字時,它會使得該弧線偏離中心。

+1

'2.1f * radius'? '(int)(2.1 * radius)'? – Patashu 2013-03-26 21:37:56

+0

@Patashu似乎已經解決了雙重問題,但這並不能解決我的圈子偏離中心問題。 – BluceRee 2013-03-26 21:49:26

回答

0

爲什麼把一個大於圓弧的數字放在你的圓心的中心是因爲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));