user462872
user462872

Reputation: 329

Copy from swing and paste in other Windows application

I'ved searched some time but no satisfying result showed thus would like to ask here.

Basicallly I have a JAVA Swing GUI table, it has some rows, let's say 3 columns each row, you see "1 david good" on a row. the content of this row is converted from a raw message, i.e. a xml message.

What I want to do is, when I selected a row and press ctrl+c, the a raw msg could be copied to clipboard then I could paste it in other Windows application like notepad or Word.

I tried toolkit to get system clipboard and put raw message in(via keylistener). But when I press ctrl+v in notepad, I still get "1 david good" as default.

I printed the raw message from clipboard in Swing code, thus I am guessing if my code only works in Swing, customized content could not be retrieved in Windows?

Could somebody tell me if it's possible to do in Swing? thanks a lot.

Upvotes: 1

Views: 1184

Answers (1)

roeygol
roeygol

Reputation: 5028

You can use this example:

String str = "Which String to copy to clipboard";
StringSelection stringSelection = new StringSelection (str);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard ();
clpbrd.setContents (stringSelection, null);

So this code can be when clicking on some button while calling it from actionPerformed()

And for pasting issue:

  public String getClipboardContents() {
    String result = "";
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    //odd: the Object param of getContents is not currently used
    Transferable contents = clipboard.getContents(null);
    boolean hasTransferableText =
      (contents != null) &&
      contents.isDataFlavorSupported(DataFlavor.stringFlavor)
    ;
    if (hasTransferableText) {
      try {
        result = (String)contents.getTransferData(DataFlavor.stringFlavor);
      }
      catch (UnsupportedFlavorException | IOException ex){
        System.out.println(ex);
        ex.printStackTrace();
      }
    }
    return result;
  }

Upvotes: 2

Related Questions