diff --git a/hw3/src/view/PhotoAlbumView.java b/hw3/src/view/PhotoAlbumView.java index d4a0090..f031a36 100644 --- a/hw3/src/view/PhotoAlbumView.java +++ b/hw3/src/view/PhotoAlbumView.java @@ -6,7 +6,9 @@ import model.PhotoAlbumModel; import javax.swing.*; import java.awt.*; +import java.util.HashMap; import java.util.List; +import java.util.Map; public class PhotoAlbumView extends JFrame implements PhotoAlbumModel.ModelChangeListener { private PhotoAlbumModel model; @@ -143,6 +145,8 @@ public class PhotoAlbumView extends JFrame implements PhotoAlbumModel.ModelChang private final JLabel textLabel = new JLabel(); private final JLabel detailsLabel = new JLabel(); + private final Map thumbnailCache = new HashMap<>(); + public PhotoListCellRenderer() { setLayout(new BorderLayout(5, 0)); @@ -170,7 +174,8 @@ public class PhotoAlbumView extends JFrame implements PhotoAlbumModel.ModelChang textLabel.setText(name); Photo photo = model.getPhotos().get(index); - ImageIcon thumbnail = loadThumbnail(photo.filePath()); + ImageIcon thumbnail = thumbnailCache.computeIfAbsent(photo.filePath(), this::loadThumbnail); + // ImageIcon thumbnail = loadThumbnail(photo.filePath()); imageLabel.setIcon(thumbnail); // Format date @@ -181,24 +186,24 @@ public class PhotoAlbumView extends JFrame implements PhotoAlbumModel.ModelChang return this; } - } - private String formatFileSize(long size) { - if (size < 1024 * 1024) { - return String.format("%.1f KB", size / 1024.0); - } else { - return String.format("%.1f MB", size / (1024.0 * 1024)); + private String formatFileSize(long size) { + if (size < 1024 * 1024) { + return String.format("%.1f KB", size / 1024.0); + } else { + return String.format("%.1f MB", size / (1024.0 * 1024)); + } } - } - private ImageIcon loadThumbnail(String path) { - try { - ImageIcon icon = new ImageIcon(path); - Image img = icon.getImage(); - Image scaledImg = img.getScaledInstance(50, 50, Image.SCALE_AREA_AVERAGING); - return new ImageIcon(scaledImg); - } catch (Exception e) { - return null; + private ImageIcon loadThumbnail(String path) { + try { + ImageIcon icon = new ImageIcon(path); + Image img = icon.getImage(); + Image scaledImg = img.getScaledInstance(50, 50, Image.SCALE_AREA_AVERAGING); + return new ImageIcon(scaledImg); + } catch (Exception e) { + return null; + } } } }