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)));
}
}
}
}
}
答案 0 :(得分: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);
}
}