The NullPointer is from the board[0][0] element being null.
for(JLabel[] row : board) {
for(JLabel s : row) {
s = new JLabel();
In this block "s" will always be null. You cannot use the
for–
each loop to alter the elements returned.
Use regular
for loops to initialize the elements of "board". Then you'll get
null from the
getIcon method in the mouse code since no icon was set.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class ChessPanelRx extends JPanel {
private static final int ROWS = 8;
private static final int COLS = 8;
// the array of JLabels
private JLabel board[][] = new JLabel[ROWS][COLS];
public ChessPanelRx() {
setLayout(new GridLayout(ROWS, COLS));
// add squares to board
boolean makeBlack = false;
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
board[i][j] = new JLabel();
board[i][j].addMouseListener(
new LabelClick(board[i][j], this.board));
add(board[i][j]);
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new ChessPanelRx());
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
public class LabelClick implements MouseListener {
private JLabel clicked;
private JLabel[][] newBoard;
private int x;
private int y;
public LabelClick(JLabel s, JLabel[][] origBoard) {
clicked = s;
newBoard = origBoard;
}
public void mouseClicked(MouseEvent e) {
// it fails here, the array is null
System.out.println(newBoard[0][0].getIcon());
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
}