If you are working on the tools development or similar product developments , then system level programming or OS interaction operations are necessary to access the native data. One of the most frequently used operation is the clipboard data. In particular, if you write program to develop own editors like notepad, clipboard operation is very common. Java provides Toolkit class which defines the static resources to access the various API to perform operation. getSystemClipboard method in Toolkit class would help you to update the content to clipboard.
This example program would store the simple to text to clipboard and then display from the clipboard. Lets look at the example.
ClipboardExample.java
package javabeat.net.core; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; public class ClipboardExample { public static void main(String[] args) { String str = "Java Clipboard Example Text!!"; Toolkit toolkit = Toolkit.getDefaultToolkit(); Clipboard clipboard = toolkit.getSystemClipboard(); StringSelection strSel = new StringSelection(str); clipboard.setContents(strSel, null); String result = null; try{ result = (String) clipboard.getData(DataFlavor.stringFlavor); }catch (IOException exception){ exception.printStackTrace(); }catch (UnsupportedFlavorException exception){ exception.printStackTrace(); } System.out.println("Clipboard Text :" + result); } }
Output…
Clipboard Text :Java Clipboard Example Text!!