2013-04-23 92 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