Implementing Copy and Paste

Implementing Copying

  1. Get the system clipboard using the getSystemClipboard() method of the java.awt.Toolkit class.
  2. Create a new object, such as a StringSelection, which implements the transferable interface and contains the data you want to copy.
  3. Put that object on the clipboard using the setContents() method of the Clipboard class.

For example,

  public void copy(TextField tf)  {
  
    StringSelection data = new StringSelection(tf.getText());
    Clipboard clipboard = Toolkit().getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(data, data);
   
  }

Implementing Pasting

  1. Get the system clipboard using the getSystemClipboard() method of the java.awt.Toolkit class.
  2. Get the clipboard's contents using the getContents() method of the Clipboard class.
  3. Get the data in a particular flavor using getTransferData().
  4. Cast the object returned to the appropriate type.

For example,

  public void paste(TextField tf)  {
  
    Clipboard clipboard = Toolkit().getDefaultToolkit().getSystemClipboard();
    Transferable data = clipboard.getContents(this);
    String s;
    try {
      s = (String) (data.getTransferData(DataFlavor.stringFlavor));
    } 
    catch (Exception ex) {
      s = data.toString();
    }
    tf.setText(s);
    
  }

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 21, 1997