Alex
Alex

Reputation: 43

GridLayout of Buttons to Output a Checkerboard

I am programming in Java and am still rather new. Experimenting with GUI Basics, I decided to make a checkerboard with all 64 cells being instances of JButtons with a filled in background. Sadly, when I tried to compile the code, only two buttons show up and neither of them are colored. I'm trying to understand the problem, but for now it seems a bit beyond me.

package checkerboard;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;

public class Checkerboard extends JFrame {

public Checkerboard() {

    JButton black = new JButton("B");
    JButton white = new JButton("W");

            black.setBackground(Color.BLACK);
            white.setBackground(Color.WHITE);



    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(8, 8));
    p1.setSize(600, 600);

    for (int i = 0; i < 8; i++) {
        if (i % 2 == 0) {
            for (int j = 0; j < 4; j++) {
                p1.add(black);
                p1.add(white);
            }
        } else {
            for (int j = 0; j < 4; j++) {
                p1.add(white);
                p1.add(black);
            }
        }
    }
    super.add(p1);
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    Checkerboard frame = new Checkerboard();
    frame.setTitle("Checkers");
    frame.setSize(600, 600);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    }
}

In experimenting with the JPanel, for some strange reason line 27 had a NullPointer Exception.

Upvotes: 4

Views: 6930

Answers (3)

Peter Vasquez
Peter Vasquez

Reputation: 1

i did this but with more to it as per HW. this but i'm told to add JPanel and Jbuttons:

Write a program that displays a checkerboard in which each white and black cell is a JButton with a background black or white, as shown in the figure below. Important! Include functionality in your program to create a listener class that implements an ActionListener.

below is what i have so far what i have but i was told that i need to add JPanel and JButtons:

import java.awt.event.*;    
import javax.swing.JButton;    
import javax.swing.JFrame;

public class CheckerBox2 extends JFrame    
  {    
    JFrame frame=new JFrame();

    public CheckerBox2()
    {
      frame.setSize(500, 500);    
      frame.setTitle("Original Checker Box");    
      //MessageLabel=new JLabel("Press button to add colors.");    
      frame.setLayout(new GridLayout(8, 8));
      for (int i=0; i<8; i++)
      {    
      for (int j=0; j<8; j++)    
      {    
      switch ((i+j)%2)    
      {    
      case 0:    
        addButton("red");    
        break;    
      case 1:    
        addButton("black");    
        break;    
      default:    
       break;    
      }      
    }

   }    
  }

  // addButton() is used to customize what the ActionListener object

  private void addButton(String color)    
  {    
    JButton button=new JButton();  
    switch (color)    
    {    
    case "red":    
      button.setBackground(Color.RED);    
      break;    
    case "black":    
      button.setBackground(Color.BLACK);
      break;    
    default:    
     break;    
    }    
    button.setOpaque(true);    
    button.setBorderPainted(false);    
    Command listener=new Command(color);    
    button.addActionListener(listener);    
    frame.add(button);    
  }

  //The Command object has its constructor read in that color and display it verbatim at the command line.

  private class Command implements ActionListener    
  {    
    private String color;    
    public Command(String c)    
    {    
      color=c;
    }

    public void actionPerformed(ActionEvent event)    
    {    
      System.out.println("Pressed "+ color + " button.");
    }    
  }

  public void run()    
    {    
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
      frame.setVisible(true);    
    }

  public static void main(String[] args)    
  {    
    CheckerBox2 box=new CheckerBox2();    
    box.run();    
  } 
}

Upvotes: 0

Instantsoup
Instantsoup

Reputation: 15265

The problem is that black and white are JButton objects and you can't add the same object more than once to a JPanel.

You need to create a new JButton each time you're adding. You can instantiate them on the fly in the loop.

for (int i = 0; i < 8; i++) {
    if (i % 2 == 0) {
        for (int j = 0; j < 4; j++) {
            p1.add(newButton("B", Color.Black));
            p1.add(newButton("W", Color.White));
        }
    } else {
        for (int j = 0; j < 4; j++) {
            p1.add(newButton("W", Color.White));
            p1.add(newButton("B", Color.Black));
       }
    }
}

Just add a method to do that.

private newButton(String label, Color background) {
    JButton button = new JButton(label);
    button.setBackground(background);
    return button;
}

Upvotes: 2

Eng.Fouad
Eng.Fouad

Reputation: 117597

This is because you are using only one instance object of JButton as a black button, and only one instance object of JButton as a white button, and you are adding the same 2 references to the JPanel p1 more and more. Thus, this won't work and you need to create an object for each button on the board. Here is how you can do such thing:

enter image description here

JButton[] blackButtons = new JButton[4 * 8];
JButton[] whiteButtons = new JButton[4 * 8];

for(int i = 0; i < blackButtons.length; i++)
{
    blackButtons[i] = new JButton("B");
    blackButtons[i].setBackground(Color.BLACK);
}
for(int i = 0; i < whiteButtons.length; i++)
{
    whiteButtons[i] = new JButton("W");
    whiteButtons[i].setBackground(Color.WHITE);
}

then you can add them like this:

for (int i = 0; i < 8; i++) {
    if (i % 2 == 0) {
        for (int j = 0; j < 4; j++) {
            p1.add(blackButtons[4 * i + j]);
            p1.add(whiteButtons[4 * i + j]);
        }
    } else {
        for (int j = 0; j < 4; j++) {
            p1.add(whiteButtons[4 * i + j]);
            p1.add(blackButtons[4 * i + j]);
        }
    }
}

add(p1);

Upvotes: 4

Related Questions