001package headfirst.proxy.virtualproxy; 002 003import java.net.MalformedURLException; 004import java.net.URL; 005import java.util.Enumeration; 006import java.util.Hashtable; 007 008import javax.swing.Icon; 009import javax.swing.JFrame; 010import javax.swing.JMenu; 011import javax.swing.JMenuBar; 012import javax.swing.JMenuItem; 013 014public class ImageProxyTestDrive { 015 ImageComponent imageComponent; 016 JFrame frame = new JFrame("CD Cover Viewer"); 017 JMenuBar menuBar; 018 JMenu menu; 019 Hashtable<String,String> cds = new Hashtable<String,String>(); 020 021 public static void main (String[] args) throws Exception { 022 ImageProxyTestDrive testDrive = new ImageProxyTestDrive(); 023 } 024 025 public ImageProxyTestDrive() throws Exception{ 026 cds.put("Ambient: Music for Airports","http://images.amazon.com/images/P/B000003S2K.01.LZZZZZZZ.jpg"); 027 cds.put("Buddha Bar","http://images.amazon.com/images/P/B00009XBYK.01.LZZZZZZZ.jpg"); 028 cds.put("Ima","http://images.amazon.com/images/P/B000005IRM.01.LZZZZZZZ.jpg"); 029 cds.put("Karma","http://images.amazon.com/images/P/B000005DCB.01.LZZZZZZZ.gif"); 030 cds.put("MCMXC A.D.","http://images.amazon.com/images/P/B000002URV.01.LZZZZZZZ.jpg"); 031 cds.put("Northern Exposure","http://images.amazon.com/images/P/B000003SFN.01.LZZZZZZZ.jpg"); 032 cds.put("Selected Ambient Works, Vol. 2","http://images.amazon.com/images/P/B000002MNZ.01.LZZZZZZZ.jpg"); 033 034 URL initialURL = new URL(cds.get("Selected Ambient Works, Vol. 2")); 035 menuBar = new JMenuBar(); 036 menu = new JMenu("Favorite CDs"); 037 menuBar.add(menu); 038 frame.setJMenuBar(menuBar); 039 040 for(Enumeration<String> e = cds.keys(); e.hasMoreElements();) { 041 String name = e.nextElement(); 042 JMenuItem menuItem = new JMenuItem(name); 043 menu.add(menuItem); 044 menuItem.addActionListener(event -> { 045 imageComponent.setIcon(new ImageProxy(getCDUrl(event.getActionCommand()))); 046 frame.repaint(); 047 }); 048 } 049 050 // set up frame and menus 051 052 Icon icon = new ImageProxy(initialURL); 053 imageComponent = new ImageComponent(icon); 054 frame.getContentPane().add(imageComponent); 055 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 056 frame.setSize(800,600); 057 frame.setVisible(true); 058 059 } 060 061 URL getCDUrl(String name) { 062 try { 063 return new URL(cds.get(name)); 064 } catch (MalformedURLException e) { 065 e.printStackTrace(); 066 return null; 067 } 068 } 069}