Other classes and methods for Copy and Paste

There are a few methods and classes outside the java.awt.datatransfer package that are relevant to copy and paste.

The getSystemClipboard() method of the java.awt.Toolkit class returns a Clipboard object which represents the system clipboard:

public abstract Clipboard getSystemClipboard()

The java.lang.SecurityManager class includes a checkSystemClipboardAccess() method that determines whether or not this program is allowed to access the system clipboard. The method is void but throws a SecurityException if access is not allowed.

public void checkSystemClipboardAccess()

The concern is that the clipboard may contain private data which the user would not want revealed to the server. As a general rule, applets loaded from web servers will not be allowed to access the system clipboard. This does not, however, apply to private clipboards you create. For example,

 try {
    SecurityManager sm = SecurityManager.getSecurityManager();
    if (sm != null) sm.checkSystemClipboardAccess();
    Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
    //... handle clipboard
  catch (SecurityException ex) {
    System.err.println("Cannot access the system clipboard");

The java.awt.TextComponent class, which both TextArea and TextField extend, has a getSelectedText() method that returns the current value of the selection as a String:

public synchronized String getSelectedText()

You'll often use this method to decide what to copy or cut. Several other TextComponent methods are also useful for manipulating the selection:

 public int  getSelectionStart()
 public void setSelectionStart(int selectionStart)
 public void setSelectionEnd(int selectionEnd)
 public void select(int selectionStart, int selectionEnd)
 public void selectAll()
 public void setCaretPosition(int position)
 public int  getCaretPosition()

The TextArea class (but not the TextField class) also has insert() and replaceRange() methods you can use for pasting:

public synchronized void insert(String s, int pos)
 public synchronized void replaceRange(String s, int start, int end)

What's the difference between these two methods? When would you use insert() and when would you use replaceRange()?

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999, 2006 Elliotte Rusty Harold
Last Modified April 25, 2006