Let me start by saying that the code works as is but I think it has a lot of redundancy. It is written this way as I kept getting nullpointerexceptions if I try to put the fileCounter > gameDiff if/else inside one for loop.
The program allows a user to create directories and add images to them. It will also display a certain number of images based on the users selection. If the user's chosen directory doesn't have enough images, it drops back to the default directory to add more.
String userDir = cboImages.getSelectedItem().toString();
File filePath = new File(baseDir + "/" + userDir + "/");
comboFile = filePath.listFiles();
int fileCounter = 0;
for (int ctr = 0; ctr < comboFile.length; ctr++) {
if (comboFile[ctr].isFile()) {
fileCounter++;
}
}
filePath = new File(baseDir + "/default/");
defaultFile = filePath.listFiles();
List<File> listShuffle = Arrays.asList(comboFile);
List<File> defaultShuffle = Arrays.asList(defaultFile);
Collections.shuffle(listShuffle);
Collections.shuffle(defaultShuffle);
if(fileCounter > gameDiff){
for (int ctr = 0; ctr < gameDiff; ctr++) {
Card card = new Card();
card.setbackImage(new ImageIcon(cardBackImage));
Image img = null;
if (listShuffle.get(ctr).isFile()) {
img = new ImageIcon(listShuffle.get(ctr).getPath()).getImage();
}
Image dimg = img.getScaledInstance(144, 216, Image.SCALE_SMOOTH);
card.setfrontImage(new ImageIcon(dimg));
// Populate card with db results
cardsList.add(card);
}
}
else{
for (int ctr = 0; ctr < gameDiff; ctr++) {
Card card = new Card();
card.setbackImage(new ImageIcon(cardBackImage));
Image img = null;
if (ctr < listShuffle.size()) {
if (listShuffle.get(ctr).isFile()) {
if (fileCounter <= gameDiff) {
img = new ImageIcon(listShuffle.get(ctr).getPath()).getImage();
}
}
} else if (ctr < gameDiff) {
if (defaultShuffle.get(ctr).isFile()) {
img = new ImageIcon(defaultShuffle.get(ctr).getPath()).getImage();
}
}
Image dimg = img.getScaledInstance(144, 216, Image.SCALE_SMOOTH);
card.setfrontImage(new ImageIcon(dimg));
// Populate card with db results
cardsList.add(card);
}
}
Using two separate groups insures that the chosen directory images get added.