I have an array of JPanels and I'm trying to add a mouseadapter to each one so it will be possible to identify which one was clicked and then change its background colour. Everything seems to work fine except when I run it from eclipse when a page will appear that says EventDispatchThread.run() line: not available, Source not found, and in the debug window it says:
Thread [AWT-Shutdown] (Running)
Daemon Thread [AWT-Windows] (Running)
Thread [AWT-EventQueue-0] (Suspended (exception ArrayIndexOutOfBoundsException))
EventDispatchThread.run() line: not available
Thread [DestroyJavaVM] (Running)
Thread [AWT-EventQueue-0] (Running)
This is the code:
private void drawBoard() {
LayoutManager layout = new GridLayout(NUMBER_OF_ROWS, NUMBER_OF_COLS);
boardPanel.setLayout(layout);
boardPanel.setPreferredSize(new Dimension(200, 400));
chessBoard = new JPanel[NUMBER_OF_ROWS][NUMBER_OF_COLS];
MoveArrays move = new MoveArrays();
move.initialisePieceMoves();
for (int i = 0; i < NUMBER_OF_ROWS; i++) {
for (int j = 0; j < NUMBER_OF_COLS; j++) {
int index = i * 4 + j;
chessBoard[i][j] = new JPanel();
chessBoard[i][j].addMouseListener(clickSquare(j, i, index, move));
chessBoard[i][j].setBackground(getColor(i,j));
if (!(boardArray.chessBoard[index].square.isEmpty())) {
Piece piece = (Piece) boardArray.chessBoard[index].square.firstElement();
JLabel pieceString = new JLabel(piece.toString());
chessBoard[i][j].add(pieceString);
}
boardPanel.add(chessBoard[i][j]);
}
}
} // drawBoard()
private MouseAdapter clickSquare(final int xCo, final int yCo, final int index, final MoveArrays move) {
return new MouseAdapter() {
public void mousePressed(MouseEvent me) {
resetColors();
JPanel selectedSquare = (JPanel) me.getSource();
selectedSquare.setBackground(selectedColor());
System.out.println("xCo: " + xCo + " yCo: " + yCo);
Vector validMoves = move.DroneMovesNorth[index].Moves;
int totalMoves = move.DroneTotalMovesNorth[index];
if (!validMoves.isEmpty()) {
for (int n = 0; n <= totalMoves; n++) {
String stringMove = validMoves.elementAt(n).toString();
int intMove = Integer.parseInt(stringMove);
System.out.println("intMove: " + intMove);
}
}
}
};
}
I think it might be the fact that I cast the me.getSource to a JPanel but shouldn't it be one anyway? If I don't put the cast it says that it cannot bind an 'Object' to a JPanel, when I do system.out.print(me.getSource()) it prints a line saying that it's a JPanel so I don't get what the problem is T_T Any help would be muchhhh appreciated!