1 27 package olstore.client; 28 29 import java.awt.datatransfer.DataFlavor; 30 import java.awt.datatransfer.Transferable; 31 import java.awt.datatransfer.UnsupportedFlavorException; 32 import java.io.IOException; 33 import java.util.Iterator; 34 import java.util.List; 35 36 import javax.swing.JComponent; 37 import javax.swing.TransferHandler; 38 39 42 class ItemPanelTransferHandler extends TransferHandler { 43 44 45 private DataFlavor itemPanelFlavor; 46 47 48 private String itemPanelType = DataFlavor.javaJVMLocalObjectMimeType + ";class=" 49 + ItemPanel.class.getName(); 50 51 54 public ItemPanelTransferHandler() { 55 try { 56 itemPanelFlavor = new DataFlavor(itemPanelType); 57 } catch (ClassNotFoundException e) { 58 System.out.println("ItemPanelTransferHandler: unable to create data flavor"); 59 } 60 } 61 62 69 public boolean importData(JComponent c, Transferable t) { 70 ItemPanel item; 71 try { 72 item = (ItemPanel) t.getTransferData(itemPanelFlavor); 73 addItemToCart(c, item.getItem()); 74 } catch (UnsupportedFlavorException e) { 75 e.printStackTrace(); 76 return false; 77 } catch (IOException e) { 78 e.printStackTrace(); 79 return false; 80 } 81 c.validate(); 82 c.repaint(); 83 return true; 84 } 85 86 90 protected Transferable createTransferable(JComponent c) { 91 ItemPanel panel = (ItemPanel) c; 92 return new ItemPanelTransferable(panel); 93 } 94 95 99 public int getSourceActions(JComponent c) { 100 return COPY_OR_MOVE; 101 } 102 103 106 protected void exportDone(JComponent c, Transferable data, int action) { 107 } 108 109 117 public boolean canImport(JComponent c, DataFlavor[] flavors) { 118 if (c instanceof ItemPanel) { 121 return false; 122 } 123 124 for (int i = 0; i < flavors.length; i++) { 125 if (itemPanelFlavor.equals(flavors[i])) { 126 return true; 127 } 128 } 129 return false; 130 } 131 132 137 private void addItemToCart(JComponent c, Item item) { 138 ShoppingCartPanel cart = (ShoppingCartPanel) c; 139 140 List items = cart.getItemsInCart(); 141 Iterator iter = items.iterator(); 142 143 OrderItem orderItem = new OrderItem(item); 144 145 if (cart.isItemInCart(orderItem)) { 147 cart.increaseQuantity(orderItem); 148 return; 149 } 150 151 cart.addNewItemToCart(orderItem); 153 } 154 155 159 class ItemPanelTransferable implements Transferable { 160 161 162 private ItemPanel panel; 163 164 168 public ItemPanelTransferable(ItemPanel itemPanel) { 169 panel = itemPanel; 170 } 171 172 179 public Object getTransferData(DataFlavor flavor) 180 throws UnsupportedFlavorException { 181 if (!isDataFlavorSupported(flavor)) { 182 throw new UnsupportedFlavorException(flavor); 183 } 184 return panel; 185 } 186 187 191 public DataFlavor[] getTransferDataFlavors() { 192 return new DataFlavor[] {itemPanelFlavor}; 193 } 194 195 200 public boolean isDataFlavorSupported(DataFlavor flavor) { 201 return itemPanelFlavor.equals(flavor); 202 } 203 } 204 } 205 | Popular Tags |