I'm trying to make chess game with java and I got image from google for pieces. Now I want to cut it to 6*2 images(Black and White ones). But I can't figure out what is wrong with this one.
public static final String PIECES_IMAGE_PATH = "Images/chess_pieces.png";
public static final int PIECE_IMAGES_INROW = 6;
public static final int PIECE_IMAGE_ROWS = 2;
BufferedImage[][] pieceIcons;
private void setupPieceImages(){
try {
BufferedImage image = ImageIO.read(new File(Config.PIECES_IMAGE_PATH));
int pieceImageWidth = image.getWidth()/Config.PIECE_IMAGES_INROW;
int pieceImageHeight = image.getHeight()/Config.PIECE_IMAGE_ROWS;
for(int x = 0; x < pieceImageHeight; x++){
for(int y = 0; y < pieceImageWidth; y++){
try{
pieceIcons[x][y] = image.getSubimage(x*pieceImageHeight,y*pieceImageWidth,pieceImageWidth,pieceImageHeight);
}catch(Exception e){
System.out.println("Error1: "+e.getMessage());
}
}
}
}catch(Exception e){
System.out.println("error2: "+e.getMessage());
}
}
Any idea why I keep getting Expection error1: null
I'm not sure why you would iterate over the amount of width/height, but I suppose you want to iterate over 2 rows of 6 columns each (or 6 columns of 2 rows each in this case):
public static final String PIECES_IMAGE_PATH = "Images/chess_pieces.png";
public static final int PIECE_IMAGES_INROW = 6;
public static final int PIECE_IMAGE_ROWS = 2;
public static void main(String args[]) {
BufferedImage[][] pieceIcons = new BufferedImage[PIECE_IMAGES_INROW][PIECE_IMAGE_ROWS];
try {
BufferedImage image = ImageIO.read(new File(Try.class.getResource(PIECES_IMAGE_PATH).toURI()));
int pieceImageWidth = image.getWidth()/PIECE_IMAGES_INROW;
int pieceImageHeight = image.getHeight()/PIECE_IMAGE_ROWS;
for(int x = 0; x < PIECE_IMAGES_INROW; x++){
for(int y = 0; y < PIECE_IMAGE_ROWS; y++){
try{
pieceIcons[x][y] = image.getSubimage(x*pieceImageWidth,y*pieceImageHeight,pieceImageWidth,pieceImageHeight);
}catch(Exception e){
System.out.println("Error1: "+e.getMessage());
}
}
}
}catch(Exception e){
System.out.println("error2: "+e.getMessage());
}
}
The error you were getting seems to be related to Error1
and that could be an indexOutOfBoundsException
in case you initialized pieceIcons
with an unexpected max amount of x/y during runtime.