swing - java Checker board issues -
so have program asks user number of rows , columns , makes checker board issue works odd numbers if user put in 9 , 9 again display checkered board if number inputted shows columns of white , black
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)); (int = 1; <= 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); } }
your example identifies numbers in single loop. instead, use nested loops identify alternating tiles:
g.setcolor(color.lightgray); … (int row = 0; row < h; row++) { (int col = 0; col < w; col++) { if ((row + col) % 2 == 0) { g.fillrect(col * tile, row * tile, tile, tile); } } }
a complete example seen here.
Comments
Post a Comment