Java AWT Clipboard get/set text data

Description

Java AWT Clipboard get/set text data

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

import javax.swing.JOptionPane;

public class Main {
  public static void main(String[] args) {
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Clipboard clipboard = toolkit.getSystemClipboard();

    // Pack data as a string in a Transferable object
    Transferable transferableData = new StringSelection("demo2s.com");
    clipboard.setContents(transferableData, null);

    Transferable data = clipboard.getContents(null);
    if (data != null && data.isDataFlavorSupported(DataFlavor.stringFlavor)) {
      try {//from   w  w w . j  a  v a  2  s .c  o  m
        String text = (String) data.getTransferData(DataFlavor.stringFlavor);
        System.out.println(text);
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      toolkit.beep();
      JOptionPane.showMessageDialog(null, "No text in the system clipboard to paste");
    }
  }
}



PreviousNext

Related