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);
}
}
感谢您的帮助我终于解决了我的问题 – Isaiah