2016-02-07 47 views
1

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

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); 
    } 
} 

回答

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

+0

感谢您的帮助我终于解决了我的问题 – Isaiah