2015-11-08 93 views
1

有人可以请帮我创建一个棋盘棋。我需要将网格的颜色更改为黑色和白色。我尝试使用if语句if (r % 2 = 0) then rectfilcolor,但它使大厅行变为彩色。网格颜色变化

package grid; 
import java.awt.Color; 
import java.awt.Graphics; 
import javax.swing.*; 

public class grid extends JPanel { 
    public static int High=640; 
    public static int width=617; 
    public static int row=3,column=3; 
    public static JFrame Frame; 

    public static void main(String[] args) { 
     grid gride= new grid(); 
     Frame= new JFrame(); 
     Frame.setSize(width, High); 
     Frame.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE); 
     Frame.setVisible(true); 
     Frame.add(gride); 
     gride.setBackground(Color.cyan); 
    } 

    public void paintComponent(Graphics g) { 
     for (int r=0; r<4; r++) { 
      g.drawLine(r*(600/3), 0, r*(600/3), 600); 

      for (int c=0; c<4; c++) { 
       g.drawLine(0,(c*(600/3)), 600, (c*(600/3))); 
      } 
     } 
    } 
} 

-------------------------------------编辑----- -----------------------------

public void paintComponent(Graphics g){ 

     for (int r=0;r<4;r++){ 
      g.drawLine(r*(600/3), 0, r*(600/3), 600); 
      if (r%2!=0){ 
       g.setColor(Color.white); 
       g.fillRect(r*(600/3), 0, r*(600/3), 600); 
      } 


     for (int c=0;c<4;c++){ 
      g.drawLine(0,(c*(600/3)), 600, (c*(600/3))); 
      if(c%2!=0){ 
       g.setColor(Color.black); 

       g.fillRect(0,(c*(600/3)), 600, (c*(600/3))); 
      } 

     } 
     } 
     } 
    } 

回答

1

一定要记得调用super.paintComponent(g)来初始化JPanel画布正确。

您可以使用g.fillRect(x, y, width, height)方法绘制每个象棋棋子。使用g.setColor(color)更改绘画的颜色。

因此:

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 

    Color[] colors = {Color.BLACK, Color.WHITE}; 
    int lengthUnit = (600/3); 
    for (int row = 0; row < 3; ++ row) { 
     for (int col = 0; col < 3; ++col) { 
      g.setColor(colors[(row + col) % 2]); // alternate between black and white 
      g.fillRect(row * lengthUnit, col * lengthUnit, lengthUnit, lengthUnit); 
     } 
    } 
} 

编辑:你是几乎没有,只需要删除嵌套的for循环中一些多余的语句...

for (int r = 0; r < 4; r++) { 
     for (int c = 0; c < 4; c++) { 
      if ((c + r) % 2 != 0) { 
       g.setColor(Color.black); 
      } else { 
       g.setColor(Color.white); 
      } 
      g.fillRect(r * (600/3), (c * (600/3)), 200, 200); 
     } 
    } 
+0

但为什么心不是我的接近方式这工作。 – user3500147

+0

@ user3500147 1)你永远不会改变绘画的颜色2)你只使用drawLines,它没有绘制区域 – Bon

+0

我在循环之后有这个。如果(r%2 == 0){g.fillrect(r * 60,0,r * 60,400)} – user3500147