4

我有一个包含 ajTextPane和 a的表单jButton,我已将其设置jTextPane Accessible Descriptiontext/html,现在我想当我单击jButton将 的内容复制jTextPane到剪贴板时,我尝试了以下代码:

 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        StringSelection stringSelection = new StringSelection (jTextPane1.getText());
        Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
        clpbrd.setContents (stringSelection, null);
    } 

但是当我过去时,它以 HTML 格式过去的文本。

我该如何解决这个问题?

4

2 回答 2

1

When I use Ctrl+C I get text copied to the clipboard without HTML. You can use the default Action with the following code:

Action copy = new ActionMapAction("Copy", textPane, "copy-to-clipboard");
JButton copyButton = new JButton(copy);

See Action Map Action for more information on how this works.

于 2013-04-24T00:04:11.763 回答
1

首先,Java 中有 2 个剪贴板(您正在使用的一个本地剪贴板和一个系统剪贴板)。是一个使用系统剪贴板的示例。看看并尝试这个 getClipboardContents 方法:

public String getClipboardContents(Clipboard clipboard) {
    String result = "";
    if (clipbloard != null){            
        //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 ex){
            //highly unlikely since we are using a standard DataFlavor
            System.out.println(ex);
            ex.printStackTrace();
          }
          catch (IOException ex) {
            System.out.println(ex);
            ex.printStackTrace();
          }
        }
    }
    return result;
}
于 2013-04-23T21:52:20.183 回答