001package headfirst.proxy.virtualproxy; 002 003import java.awt.Component; 004import java.awt.Graphics; 005import java.net.URL; 006 007import javax.swing.Icon; 008import javax.swing.ImageIcon; 009 010class ImageProxy implements Icon { 011 ImageIcon imageIcon; 012 URL imageURL; 013 Thread retrievalThread; 014 boolean retrieving = false; 015 016 public ImageProxy(URL url) { imageURL = url; } 017 018 public int getIconWidth() { 019 if (imageIcon != null) { 020 return imageIcon.getIconWidth(); 021 } else { 022 return 800; 023 } 024 } 025 026 public int getIconHeight() { 027 if (imageIcon != null) { 028 return imageIcon.getIconHeight(); 029 } else { 030 return 600; 031 } 032 } 033 034 public void paintIcon(final Component c, Graphics g, int x, int y) { 035 if (imageIcon != null) { 036 imageIcon.paintIcon(c, g, x, y); 037 } else { 038 g.drawString("Loading CD cover, please wait...", x+300, y+190); 039 if (!retrieving) { 040 retrieving = true; 041 042 retrievalThread = new Thread(() -> { 043 try { 044 imageIcon = new ImageIcon(imageURL, "CD Cover"); 045 c.repaint(); 046 } catch (Exception e) { 047 e.printStackTrace(); 048 } 049 }); 050 retrievalThread.start(); 051 } 052 } 053 } 054}