Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am trying to solve the N-Queens problem. In my frame, I have a clickable chess

ID: 3574955 • Letter: I

Question

I am trying to solve the N-Queens problem. In my frame, I have a clickable chessboard of JButtons when if you click one a Queen gets placed there if there isn't a queen there to start. It removes a queen if there is already a queen there. There is also an ArrayList of Boxes objects that keep track of the Boxes occupied by Queens. The problem I am having initially seems to be my action listener for the button that tells the user if the solution is correct or not.

But I'm not sure if that's the problem exactly. When I run the program and press the "safe" JButton, it displays the correct message when there are no queens on the board. But when I add a queen, then take it away, it doesn't show the message. I've debugged, and I know that the Boxes are being removed correctly, so it might be something else. Here is the whole class.

package edu.miamioh.bergmahb;

import javax.swing.*;

import javax.swing.border.LineBorder;

import java.awt.Color;

import java.awt.GridLayout;

import java.awt.Image;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.*;

public class ChessBoardGUI extends JFrame {

   ImageIcon queenP = new ImageIcon(getClass().getResource("/images/queen.png"));

   Image img = queenP.getImage();

   Image newImg = img.getScaledInstance(40, 40, java.awt.Image.SCALE_SMOOTH);

   ImageIcon queenPic = new ImageIcon(newImg);

   private static JButton tip;

   private static JButton safe;

   private static JLabel ifNotSafe;

   private JButton[][] chessBoxes = new JButton[8][8];

   public static JPanel chessBoard;

   public static ArrayList<Boxes> queensOnBoard = new ArrayList<Boxes>();

   /*

   * Makes the whole frame for the ChessBoard

   */

   public ChessBoardGUI() {

       createBoard();

       createOtherThings();

       setSize(500, 500);

   }

   /*

   * Creates the Tip and Safe buttons And Label to display when the solution

   * is incorrect

   */

   public void createOtherThings() {

       safe = new JButton("Safe?");

       tip = new JButton("Tip");

       ifNotSafe = new JLabel();

       ButtonListen1 safeListener = new ButtonListen1();

       ButtonListen2 tipListener = new ButtonListen2();

       safe.addActionListener(safeListener);

       tip.addActionListener(tipListener);

   }

   /*

   * ActionListener for the safe button

   */

   class ButtonListen1 implements ActionListener {

       @Override

       public void actionPerformed(ActionEvent e) {

           // Tells user which queens are not safe

           if (checkSolution(queensOnBoard) == true) {

               ifNotSafe.setText("This Solution is correct so far");

           } else {

               ifNotSafe.setText("This Solution is incorrect so far");

               // *********Also highlight the queens that are not safe******

           }

       }

   }

   /*

   * ActionListener for the tip button

   */

   class ButtonListen2 implements ActionListener {

       @Override

       public void actionPerformed(ActionEvent e) {

           // ********Tells the user other places to put queens********

       }

   }

   /*

   * Creates the overall ChessBoard

   */

   public void createBoard() {

       GridLayout gridLayout = new GridLayout();

       gridLayout.setRows(8);

       gridLayout.setColumns(8);

       chessBoard = new JPanel(gridLayout);

       chessBoard.setSize(400, 400);

       chessBoard.setBorder(new LineBorder(Color.BLACK));

       chessBoard.setVisible(true);

       /*

       * Loops through to add each chessBox to the chessBoard

       */

       for (int x = 0; x < 8; x++) {

           for (int y = 0; y < 8; y++) {

               chessBoxes[x][y] = new JButton();

               chessBoxes[x][y].setBorderPainted(false);

               /*

               * Assigns a color to every other box

               */

               if ((x + y) % 2 == 0) {

                   chessBoxes[x][y].setBackground(Color.BLACK);

               } else {

                   chessBoxes[x][y].setBackground(Color.WHITE);

               }

               chessBoxes[x][y].setOpaque(true);

               chessBoard.add(chessBoxes[x][y]);

               // Adds the ActionListener to each chessBox

               BoxListener boxListen = new BoxListener();

               chessBoxes[x][y].addActionListener(boxListen);

           }

       }

   }

   /*

   * Action Listener for if the individual boxes on the ChessBoard are clicked

   */

   class BoxListener implements ActionListener {

       @Override

       public void actionPerformed(ActionEvent e) {

           JButton button = ((JButton) e.getSource());

           // Runs through a loop to find the X and Y coordinate of the

           // JButton(Box) that was clicked

           for (int x = 0; x < 8; x++) {

               for (int y = 0; y < 8; y++) {

                   if (chessBoxes[x][y] == button) {

                       /*

                       * If there is No Queen at that JButton

                       */

                       if ((isOnBoard(queensOnBoard, x, y) == false)) {

                           // Makes sure the user can not place more than

                           // 8 Queens on the board

                           if (queensOnBoard.size() < 8) {

                               // Sets Picture of Queen on box

                               button.setIcon(queenPic);

                               // Adds box to the ArrayList of occupied boxes

                               queensOnBoard.add(new Boxes(x, y));

                           }

                       }

                       /*

                       * If there is a Queen at that JButton

                       */

                       else {

                           removeQueen(queensOnBoard, x, y);

                           button.setIcon(null);

                       }

                   }

               }

           }

       }

   }

   /*

   * Checks if a certain Box has a Queen in it or not

   *

   * @param a Is the ArrayList of the Boxes currently occupied by Queens

   *

   * @param x Is the X coordinate of the Box that was clicked

   *

   * @param y Is the Y coordinate of the Box that was clicked

   */

   public boolean isOnBoard(ArrayList<Boxes> a, int x, int y) {

       for (int i = 0; i < a.size(); i++) {

           if (((a.get(i)).getX() == x) && ((a.get(i)).getY() == y)) {

               return true;

           }

       }

       return false;

   }

   /*

   * Removes a Queen from the GUI at the specified Box (JButton)

   *

   * @param a Is the ArrayList of the Boxes currently occupied by Queens

   *

   * @param x Is the X coordinate of the Box that was clicked

   *

   * @param y Is the Y coordinate of the Box that was clicked

   */

   public void removeQueen(ArrayList<Boxes> a, int x, int y) {

       /*

       * Removes the box from the overall ArrayList of Boxes Occupied by

       * queens according to the x and y location

       */

       for (int i = 0; i < a.size(); i++) {

           if (((a.get(i)).getX() == x) && ((a.get(i)).getY() == y)) {

               queensOnBoard.remove(i);

           }

       }

   }

   /*

   * Return to the user which queens need to be highlighted

   *

   * @param queensOnBoard Is the ArrayList of Boxes that are occupied by

   * Queens currently on the ChessBoard

   */

   public void conflictingQueens(ArrayList<Boxes> queensOnBoard) {

       // *******Call the highlightBoxes method using the ArrayList

       // Of Boxes you get from this method

   }

   /*

   * Checks to see if solution is correct thusfar

   *

   * @param queensOnBoard Is the ArrayList of Boxes that are occupied by

   * Queens currently on the ChessBoard

   */

   public boolean checkSolution(ArrayList<Boxes> queensOnBoard) {

       int size = queensOnBoard.size();

       if (size < 1) {

           return true;

       }

       if (size == 1) {

           return true;

       }

       for (int x = 0; x < size - 1; x++) {

           for (int y = 1; y < size; y++) {

               // Checks if Queen is safe from horizontal attacks

               if (queensOnBoard.get(x).getX() == queensOnBoard.get(y).getX()) {

                   return false;

                   // Checks if Queen is safe from vertical attacks

               } else if (queensOnBoard.get(x).getY() == queensOnBoard.get(y).getY()) {

                   return false;

                   // Checks if Queen is safe from diagonal attacks

                   // Uses diagonalAttack(queensOnBoard) as a helper method

               } // else if(){

                   // return false;

                   // }

           }

       }

       return true;

   }

   /*

   * Checks to see if the queen is safe from diagonal attacks

   *

   *

   */

   // public boolean diagonalAttack(ArrayList<Boxes> queensOnBoard){

   //********

   // }

   /*

   * Highlights boxes that are conflicting with one another

   *

   * @param highlight Is the ArrayList of Boxes that are occupied by Queens

   * currently on the ChessBoard

   */

   public void highlightBoxes(ArrayList<Boxes> highlight) {

       int size1 = highlight.size();

       int size2 = queensOnBoard.size();

       // When there aren't any queens at risk, this block

       // changes the background colors of the boxes back to

       // Their respective color

       if ((size1 == 0) && size1 == 1) {

           for (int x = 0; x < 8; x++) {

               for (int y = 0; y < 8; y++) {

                   chessBoxes[x][y] = new JButton();

                   chessBoxes[x][y].setBorderPainted(false);

                   /*

                   * Assigns a color to every other box

                   */

                   if ((x + y) % 2 == 0) {

                       chessBoxes[x][y].setBackground(Color.BLACK);

                   } else {

                       chessBoxes[x][y].setBackground(Color.WHITE);

                   }

               }

           }

       }

       // Runs through both the highlight and queensOnBoard ArrayLists and

       // changes the background for the Queens at risk

       for (int b = 0; b < size2; b++) {

           for (int a = 0; a < size1; a++) {

               if ((highlight.get(a).getX() == queensOnBoard.get(b).getX())

                       && (highlight.get(a).getY() == queensOnBoard.get(b).getY())) {

                   int x = queensOnBoard.get(b).getX();

                   int y = queensOnBoard.get(b).getY();

                   chessBoxes[x][y].setBackground(Color.RED);

               }

           }

       }

   }

   /*

   * Main method to run the program

   *

   * @param args Is the String of args given to the console to run the

   * operations of the program

   */

   public static void main(String[] args) {

       JFrame frame = new ChessBoardGUI();

       frame.add(chessBoard);

       chessBoard.setLocation(50, 50);

       JPanel panel1 = new JPanel();

       panel1.add(safe);

       panel1.add(tip);

       panel1.add(ifNotSafe);

       frame.add(panel1);

       frame.setTitle("ChessBoard");

       frame.setVisible(true);

       frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

   }

}

Explanation / Answer



as per my knowledge I wrote this . I think it will be usefull to u
public class Queen {
    //Number of rows or columns
    public static final int BOARD_SIZE = 8;
    boolean[][] board;
    //Indicate an empty square
    public static final boolean EMPTY = false;
    //Indicate a square which containing a queen
    public static final boolean QUEEN = true;
    //Number of moves
    public static final int MOVES = 4;
    //Horizontal moves
    int[] horizontal;
    //Vertical moves
    int[] vertical;
    public int queens = 0;
    public Queen() {
        //Constructor creates an empty board
        board = new boolean[BOARD_SIZE][BOARD_SIZE];
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[row].length; col++) {
                board[row][col] = EMPTY;
            }
        }
        horizontal = new int[MOVES];
        vertical = new int[MOVES];
        // up right
        horizontal[0] = -1;
        vertical[0] = 1;
        // down left
        horizontal[1] = 1;
        vertical[1] = -1;
        // up left
        horizontal[2] = -1;
        vertical[2] = -1;
        // down right
        horizontal[3] = 1;
        vertical[3] = 1;
    }
    public boolean placeQueens (int column) {
        if (column >= BOARD_SIZE) {
            return true;
        }
        else {
            boolean queenPlaced = false;
            int row = 0;
            while (!queenPlaced && row < BOARD_SIZE) {
                if (isUnderAttack(row, column)) {
                    ++row;
                }// end if
                else{
                    setQueen(row, column);
                    queenPlaced = placeQueens(column + 1);
                    if (!queenPlaced) {
                        removeQueen(row,column);
                        ++row;
                    }// end if
                }// end else
            }// end while
            return queenPlaced;
        }// end else
    }
    private void removeQueen(int row, int column) {
        board[row][column] = EMPTY;
        System.out.printf("queen REMOVED from [%d][%d] ", row, column);
    --queens;
    }
    private void setQueen(int row, int column) {
        board[row][column] = QUEEN;
        System.out.printf("queen PLACED in [%d][%d] ", row, column);
        ++queens;
    }
    public boolean isUnderAttack(int row, int col) {
        boolean condition = false;
        // check row
        for (int column = 0; column < BOARD_SIZE; column++) {
            if ((board[row][column] == true)) {
                condition = true;
            }
        }
        // check column
        for (int row_ = 0; row_ < board.length; row_++) {
            if (board[row_][col] == true) {
                        condition = true;
            }
        }
        // check diagonal
        for (int row_ = row, col_ = col; row_ >= 0 && col_ < 8; row_ += horizontal[0], col_ += vertical[0]) {
            if (board[row_][col_] == true) {
                condition = true;
            }
        }
        for (int row_ = row, col_ = col; row_ < 8 && col_ >= 0; row_ += horizontal[1], col_ += vertical[1]) {
            if (board[row_][col_] == true) {
                condition = true;
            }
        }
        for (int row_ = row, col_ = col; row_ >= 0 && col_ >= 0; row_ += horizontal[2], col_ += vertical[2]) {
            if (board[row_][col_] == true) {
                condition = true;
            }
        }
        for (int row_ = row, col_ = col; row_ < 8 && col_ < 8; row_ += horizontal[3], col_ += vertical[3]) {
            if (board[row_][col_] == true) {
                condition = true;
            }
        }
        return condition;
    }
    public void displayBoard () {
        int counter = 0;
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[row].length; col++) {
                if (board[row][col] == true) {
                    System.out.printf("|%s|", "x");
                    counter++;
                }
                else {              
                    System.out.printf("|%s|", "o");
                }
            }
            System.out.println();
        }
        System.out.printf("%d queens has been placed ", counter);
    }
}
output:

|x||o||o||o||o||o||o||o|
|o||o||o||o||o||o||x||o|
|o||o||o||o||x||o||o||o|
|o||o||o||o||o||o||o||x|
|o||x||o||o||o||o||o||o|
|o||o||o||x||o||o||o||o|
|o||o||o||o||o||x||o||o|
|o||o||x||o||o||o||o||o|

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote