/Users/lyon/j4p/src/gui/tree/JLabelTransferable.java

1    package gui.tree; 
2     
3    import javax.swing.*; 
4    import java.awt.datatransfer.DataFlavor; 
5    import java.awt.datatransfer.Transferable; 
6    import java.io.ByteArrayInputStream; 
7    import java.io.ByteArrayOutputStream; 
8    import java.io.IOException; 
9    import java.io.OutputStreamWriter; 
10    
11   public class JLabelTransferable implements Transferable { 
12       public JLabelTransferable(JLabel label) { 
13           this.label = label; 
14       } 
15    
16       // Implementation of the Transferable interface 
17       public DataFlavor[] getTransferDataFlavors() { 
18           return flavors; 
19       } 
20    
21       public boolean isDataFlavorSupported(DataFlavor fl) { 
22           for (int i = 0; i < flavors.length; i++) { 
23               if (fl.equals(flavors[i])) { 
24                   return true; 
25               } 
26           } 
27    
28           return false; 
29       } 
30    
31       public Object getTransferData(DataFlavor fl) { 
32           if (!isDataFlavorSupported(fl)) { 
33               return null; 
34           } 
35    
36           if (fl.equals(DataFlavor.stringFlavor)) { 
37               // String - return the text as a String 
38               return label.getText() + " (DataFlavor.stringFlavor)"; 
39           } else if (fl.equals(jLabelFlavor)) { 
40               // The JLabel itself - just return the label. 
41               return label; 
42           } else { 
43               // Plain text - return an InputStream 
44               try { 
45                   String targetText = label.getText() + " (plain text flavor)"; 
46                   int length = targetText.length(); 
47                   ByteArrayOutputStream os = new ByteArrayOutputStream(); 
48                   OutputStreamWriter w = new OutputStreamWriter(os); 
49                   w.write(targetText, 0, length); 
50                   w.flush(); 
51                   byte[] bytes = os.toByteArray(); 
52                   w.close(); 
53                   return new ByteArrayInputStream(bytes); 
54               } catch (IOException e) { 
55                   return null; 
56               } 
57           } 
58       } 
59    
60       // A flavor that transfers a copy of the JLabel 
61       public static final DataFlavor jLabelFlavor = 
62               new DataFlavor(JLabel.class, "Swing JLabel"); 
63    
64       private JLabel label;       // The label being transferred 
65       private static final DataFlavor[] flavors = 
66               new DataFlavor[]{ 
67                   DataFlavor.stringFlavor, 
68                   new DataFlavor("text/plain; charset=ascii", "ASCII text"), 
69                   jLabelFlavor 
70               }; 
71   }