2013-04-23 170 views
4

我有包含jTextPanejButton一个形式,我给自己定的jTextPaneAccessible Descriptiontext/html,现在我想,当我在jButton点击到jTextPane的内容复制到剪贴板我,我试过这段代码:复制的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格式过去文本。

我该如何解决这个问题?

回答

1

首先,Java中有2个剪贴板(本地和系统之一,您正在使用)。 Here是一个使用系统剪贴板的例子。看看并试试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; 
} 
+0

正如我所看到的,问题在于设置或获取内容,它的ant将文本从JTextpane转换为纯文本(剥离HTML标签) – MadProgrammer 2013-04-23 22:09:39

1

当我使用Ctrl + C时,我将文本复制到没有HTML的剪贴板。你可以使用默认的动作用下面的代码:

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

关于如何工作的更多信息,请Action Map Action