java Checker board问题

时间:2016-02-07 22:39:28

标签: java swing grid-layout chess

所以我有这个程序要求用户输入多个行和列,然后将它变成一个棋盘但我的问题是它只适用于奇数,如果用户再次输入9和9它会显示一个方格板,但如果输入偶数,它只显示白色和黑色的列

import javax.swing.*;
import java.awt.*;

public class Checkers {

    public static void main(String[] args) {
        JFrame theGUI = new JFrame();
        theGUI.setTitle("Checkers");
        String inputStr = JOptionPane.showInputDialog("Number of rows");
        if (inputStr == null) return;
        int rows = Integer.parseInt(inputStr);
        inputStr = JOptionPane.showInputDialog("Number of Columns");
        if (inputStr == null) return;
        int cols = Integer.parseInt(inputStr);
        theGUI.setSize(cols * 50 , rows * 50);
        theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container pane = theGUI.getContentPane();
        pane.setLayout(new GridLayout(rows, cols));
        for (int i = 1; i <= rows * cols ;i ++) {
            if(i % 2 == 0){
              ColorPanel panel = new ColorPanel(Color.white);
              pane.add(panel);
            }else{
                ColorPanel panel = new ColorPanel(Color.black);
                pane.add(panel);
            }
        }
        theGUI.setVisible(true);
    } 
}

1 个答案:

答案 0 :(得分:3)

您的示例在单个循环中标识偶数。相反,使用嵌套循环来识别交替切片:

g.setColor(Color.lightGray);
…
for (int row = 0; row < h; row++) {
    for (int col = 0; col < w; col++) {
        if ((row + col) % 2 == 0) {
            g.fillRect(col * TILE, row * TILE, TILE, TILE);
        }
    }
}

看到一个完整的例子here

image