hw3: PhotoAlbumView: improve performance by caching thumbnails
This commit is contained in:
parent
d4705dc11e
commit
c10ba4b2fc
@ -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<String, ImageIcon> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user