Advertisement
Guest User

Untitled

a guest
Jul 27th, 2016
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. public static void main(String[] args) throws Exception {
  2.         // The clipboard
  3.    
  4.         final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
  5.         // read clipboard and take ownership to get the FlavorListener notified
  6.         // when the content has changed but the owner has not
  7.         processClipboard(cb);
  8.         cb.addFlavorListener(new FlavorListener() {
  9.             @Override
  10.             public void flavorsChanged(FlavorEvent e) {
  11.                 processClipboard(cb);
  12.             }
  13.         });
  14.         // keep thread for testing
  15.         Thread.sleep(100000L);
  16.     }
  17.  
  18.     public static void processClipboard(Clipboard cb) {
  19.         // gets the content of clipboard
  20.         Transferable trans = cb.getContents(null);
  21.         if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
  22.             try {
  23.                 // cast to string
  24.                 String s = (String) trans
  25.                         .getTransferData(DataFlavor.stringFlavor);
  26.                 System.out.println(s);
  27.                 // only StringSelection can take ownership, i think
  28.                 StringSelection ss = new StringSelection(s);
  29.                 // set content, take ownership
  30.                 cb.setContents(ss, ss);
  31.             } catch (UnsupportedFlavorException e2) {
  32.                 e2.printStackTrace();
  33.             } catch (IOException e2) {
  34.                 e2.printStackTrace();
  35.             }
  36.         }
  37.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement