2016-07-06 80 views
0

我試圖做交替顏色的靶心,但每次運行這段代碼時,我都會得到一種統一的顏色。我嘗試在for循環結束時使用repaint(),但它沒有幫助。交替顏色的靶心

import java.awt.Color; 
import java.awt.Graphics; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Unit5Activity1 extends JPanel{ 

    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     Color color1 = new Color(100, 199, 100); 
     Color color2 = new Color(208, 180, 45); 

     for(int i = 5; i > 0; i--){ 
      if(i == 1 || i == 3 || i == 5) { 
       g.setColor(color1); 
       g.fillOval(250 + i*25, 250 + i*25, 250 - 50*i, 250 - 50*i); 
      } 

      else if(i == 2 || i == 4){ 
       g.setColor(color2); 
       g.fillOval(250 + i*25, 250 + i*25, 250 - 50*i, 250 - 50*i); 
      } 
     } 
    } 





    public static void main(String[] args){ 
     Unit5Activity1 panel = new Unit5Activity1(); 
     JFrame application = new JFrame(); 

     application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     application.add(panel); 
     application.setSize(500, 500); 
     application.setVisible(true); 
    }//main 

}//class 

回答

3
g.fillOval(250 + i*25, 250 + i*25, 250 - 50*i, 250 - 50*i); 

不要做數學計算的方法的參數。當你這樣做時,你無法驗證計算是否正確。

取而代之的是創建變量並在計算中使用變量,然後您可以調試代碼以查看它是否以您期望的方式工作。

所以,你的代碼應該是這樣的:

for(int i = 5; i > 0; i--) 
{ 
    int x = 250 + i*25; 
    int y = x; 
    int width = 250 - 50*i; 
    int height = width; 
    System.out.println(x + " : " + width); 

    if(i == 1 || i == 3 || i == 5) 
    { 
     g.setColor(color1); 
    } 

    else if(i == 2 || i == 4) 
    { 
     g.setColor(color2); 
    } 

    g.fillOval(x, y, width, height); 
} 

你想先畫的最大圓。因此,通過每次循環:

  1. 的x/y值應增加和
  2. 寬度/高度應適當減少

現在你可以驗證你的邏輯正確與否。