2016-02-07 134 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