-1

I'm trying to practice my rather poor Java, and I came across this site. http://www.homeandlearn.co.uk/exercises/programming_exercises.html

I am doing exercise 6, and the exercise is to create a 2d string checkerboard using the words black and white. This looks something like

http://www.homeandlearn.co.uk/exercises/images/checkerboard.png

I did this with not too much problem, but I wanted to challenge myself further. I modified the program (or tried to) in order to create an ACTUAL 2d checkerboard, like a chessboard, but failed miserably.

Here's my code with swing:

import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class exercise6 extends JFrame{
public Image black; 
public Image white; 
JPanel p = new JPanel();
public int rows = 8;
public Image checkerboard[][] = new Image[rows][rows];
   public static void main(String[] args) {



   for(int i=0; i<rows; i++) {
        for(int j=0; j<rows; j++) {

            if(i == j)
               checkerboard[i][j] = white;
           else if(i== j-2)
                checkerboard[i][j] = white;
           else if(i== j+2)
               checkerboard[i][j] = white;
           else if(i==j-4)
               checkerboard[i][j] = white;
           else if(i==j+4)
               checkerboard[i][j] = white;
           else
               checkerboard[i][j] = black;
       }    
   }
   new exercise6();
}//ends the main method

public exercise6() {
    super("Checkerboard");
    setResizable(false);
    setSize(800,800);
    setDefaultCloseOperation(CLOSE_ON_EXIT);
    p.add(checkerboard);
    add(p);
    setVisible(true);


}
}

Here's my code when it worked:

public class checkerboard{

public static void main(String[] args) {
 int rows = 8;
String checkerboard[][] = new String[rows][rows];   

for(int i=0; i<rows; i++) {
    for(int j=0; j<rows; j++) {

        if(i == j)
            checkerboard[i][j] = "white ";
        else if(i== j-2)
            checkerboard[i][j] = "white ";
        else if(i== j+2)
            checkerboard[i][j] = "white ";
        else if(i==j-4)
            checkerboard[i][j] = "white ";
        else if(i==j+4)
            checkerboard[i][j] = "white ";
        else if(i==j+6)
            checkerboard[i][j] = "white ";
        else if(i==j-6)
            checkerboard[i][j] = "white ";
        else
            checkerboard[i][j] = "black ";
        System.out.print(checkerboard[i][j]);
    }
    System.out.println();
    }   
}

}
  • Could you explain what goes wrong ? Thank you. –  May 16 '15 at 18:31
  • Yes, it compiles, but command prompt throws me like 8 "non-static variables cannot be referenced from a static context" errors, and I seem to have messed up the default close operation line. – trailrunnersquared May 16 '15 at 18:57
  • No it doesn't compile for the error reason noted above. – Hovercraft Full Of Eels May 16 '15 at 18:58
  • My bad sorry I didn't know if you meant that it passed through the compiler without errors or if I could compile it. Ok thanks, I'll keep that in mind when I code more things in the future – trailrunnersquared May 16 '15 at 19:00
  • 1
    Take a look at http://stackoverflow.com/a/30200222/300257 to see what's involved in making a Swing checkerboard. It involves using the [model / view / controller pattern](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) and modelling the squares. – Gilbert Le Blanc May 16 '15 at 19:11
  • lol I wasn't going to program a game of checkers or chess I just wanted to make the design for it (: – trailrunnersquared May 16 '15 at 20:09

1 Answers1

1

Suggestions:

  • To draw a checkerboard, you must draw inside of something, and I suggest that you draw inside of a JPanel, or more precisely inside of a class that extends JPanel.
  • You would then draw within the JPanel's paintComponent(Graphics g) method.
  • When overriding this method, make sure to first call the super's method, super.paintComponent(g) so that the JPanel can do its own housekeeping painting of itself and its child components.
  • A simple way to tell which square to paint white or black is to see if the row and column are even and odd together, in other words, if the square's row and column are both even or both odd, paint them one color, if one is even and the other is odd, paint them another color. This can be tested using the mod operator, % and testing if the variables mod 2 are the same: if (row % 2 == col % 2).
  • You can't add an array of image to a JPanel and have your code compile. Never make up code by guessing, but instead use the Java API to see exactly what methods are allowed for each of the core Java classes.

For example:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;

// extend JPanel so you can draw within it
public class SimpleCheckerboard extends JPanel {
   public static final int ROWS = 8;
   private static final int PREF_W = 60 * ROWS;
   private static final int PREF_H = PREF_W;

   public SimpleCheckerboard() {
      // TODO Auto-generated constructor stub
   }

   // the method that does the drawing:
   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      for (int row = 0; row < ROWS; row++) {
         for (int col = 0; col < ROWS; col++) {
            // choose a Color black or white depending on row and col

            Color c = Color.white;
            if (row % 2 == col % 2) {
               c = Color.black;
            }

            // this would work too!
            // Color c = (row % 2 == col % 2) ? Color.BLACK : Color.WHITE;
            g.setColor(c);

            int x = (col * getWidth()) / ROWS;
            int y = (row * getHeight()) / ROWS;
            int w = getWidth() / ROWS;
            int h = getHeight() / ROWS;

            g.fillRect(x, y, w, h);
         }
      }
   }

   @Override  // set size of our GUI
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private static void createAndShowGui() {
      SimpleCheckerboard mainPanel = new SimpleCheckerboard();

      JFrame frame = new JFrame("SimpleCheckerboard");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      // call our code in a Swing thread-safe way:
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • So what I did was not even close to being correct. I didn't paint anything, and you found a clever way to incorporate and condense my "algorithm" (or lack thereof) into the painting thingy. Thanks. I'll think about this and see if I can brush up on my swing before I try anything else with images and make myself look like a fool. – trailrunnersquared May 16 '15 at 20:27
  • @trailrunnersquared: If you want to learn Swing coding, you can find links to the Swing tutorials and to other Swing resources here: [Swing Info](http://stackoverflow.com/tags/swing/info). I have to warn you that the Java powers that be have decided not to enhance the library further and instead have put the energies behind JavaFx as its replacement. – Hovercraft Full Of Eels May 16 '15 at 20:53