package cse1030; import java.awt.MediaTracker; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.ImageIcon; /** * A model for the image viewer app. The model represents a sequence of * images. It supports traversal through the sequence of images by providing * methods for getting the previous image in the sequence, the current image * in the sequence, and the next image in the sequence. Images * * @author CSE1030Z * */ public class ViewerModel { private static final ImageIcon EMPTY_IMAGE = new ImageIcon(); private int currentImageIndex; private List images; /** * Create the model. */ public ViewerModel() { this.currentImageIndex = -1; this.images = new ArrayList(); } /** * Get the current image in the model. Returns an empty image if the model has no images. * * @return the current image if the model has one or more images, or an empty * image otherwise */ public ImageIcon getCurrentImage() { if (this.currentImageIndex < 0) { return EMPTY_IMAGE; } return this.images.get(this.currentImageIndex); } /** * Get the next image in the model and makes the next image the current image. * Returns the current image if the current image is the last image in the * model. Returns an empty image if the model has no images. * * @return the next image in the model */ public ImageIcon getNextImage() { if (this.currentImageIndex == this.images.size() - 1) { return this.getCurrentImage(); } else if (this.images.isEmpty()) { return EMPTY_IMAGE; } else { this.currentImageIndex++; return this.images.get(this.currentImageIndex); } } /** * Get the previous image in the model and makes the previous image the current image. * Returns the current image if the current image is the first image in the * model. Returns an empty image if the model has no images. * * @return the previous image in the model */ public ImageIcon getPreviousImage() { if (this.currentImageIndex == 0) { return this.getCurrentImage(); } else if (this.images.isEmpty()) { return EMPTY_IMAGE; } else { this.currentImageIndex--; return this.images.get(this.currentImageIndex); } } /** * Clear the images held by the model. */ public void clearImages() { this.currentImageIndex = -1; this.images.clear(); } /** * Read an array of image files into the model. The images are added to the end * of the sequence of images in the model. Image file formats supported * include JPEG, PNG, and GIF. * * @param files an array of File references to open */ public void openImages(File[] files) { List icons = new ArrayList(); for (File f : files) { ImageIcon icon = new ImageIcon(f.getAbsolutePath()); if (icon.getImageLoadStatus() == MediaTracker.COMPLETE) { icons.add(icon); } } if (this.currentImageIndex < 0 && icons.size() > 0) { this.currentImageIndex = 0; } this.images.addAll(icons); } }