I am making a chess game in which each tile(class) holds an X and Y position and the board is represented by a two dimensional array of tiles. I have a class called board which extends JComponent and my main function adds the board to a JFrame. Based on what I have read, the paint function is called implicitly(not sure). The problem is that when i tried printing the x and y position of the tiles(being iterated over) it prints all of the x and y positions three times, which led me to believe that paint is being called more than once.
Board class:
class Board extends JComponent{
Tile[][] board1;
Board(Pieces p,boolean containPiece){
//initialize board
board1 = board; // set attribute
}
public void paint(Graphics g){
for(int i = 0; i < board1.length; i++){
for(int j = 0; j < board1.length; j++){
g.fillRect(board1[j][i].xPosition+130, board1[j][i].yPosition+20,board1[j][i].tileWidth,board1[j][i].tileHeight);
System.out.println(j+ " "+ " " + i );
if((j+i)%2 == 0){
g.setColor(Color.BLACK);
}
else{
g.setColor(Color.WHITE);
}
}
}
}
}
Main class:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(350,10,700, 600);
Knight k = new Knight("Knight","K","white",4,5,3);
frame.getContentPane().add(new Board(k,true));
frame.setVisible(true);
}
the output is the following(not in same format as code but same content) but repeated twice more:
0 0, 1 0, 2 0, 3 0, 4 0, 5 0, 6 0, 7 0,
0 1 ,1 1 ,2 1 ,3 1 ,4 1 ,5 1 ,6 1 ,7 1,
0 2 ,1 2 ,2 2 ,3 2 ,4 2 ,5 2 ,6 2 ,7 2 ,
0 3 ,1 3 ,2 3 ,3 3 ,4 3 ,5 3 ,6 3 ,7 3 ,
0 4 ,1 4 ,2 4 ,3 4 ,4 4 ,5 4 ,6 4 ,7 4,
0 5 ,1 5 ,2 5 ,3 5 ,4 5 ,5 5 ,6 5 ,7 5 ,
0 6 ,1 6 ,2 6 ,3 6 ,4 6 ,5 6 ,6 6 ,7 6 ,
0 7 ,1 7 ,2 7 ,3 7 ,4 7 ,5 7 ,6 7 ,7 7