簡體   English   中英

從網站復制到JTextPane給我不必要的格式和html標簽

[英]Copying from a website into a JTextPane is giving me unwanted formatting and html tags

以下是一些背景信息:

我有一個擴展JTextPane的類,當您從網站復制文本到它時,它會給我不必要的格式元素和標簽。 iframe,字體等。JTextPane的類型為html / text,需要保持這種方式,因為我將代碼的另一部分中的鏈接更改為可點擊的鏈接。

據我所知,當我從Web復制並粘貼到JTextPane時,它會自動嘗試保持格式,我不希望這種情況發生。

需要記住的一些事情,我正在使用HTMLEditorKit,並且不想在我的存儲庫中添加另一個大型工具。 有沒有一種簡單的方法可以獲取文本,而不是粘貼所有元素和格式?

如果您不想使用DefaultEditorKit,而只想將文本復制並粘貼到HtmlEditorKit,則可以嘗試編寫自己的粘貼代碼,

textPane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), "paste");

textPane.getActionMap().put("paste", pasteAction);

class PasteAction extends AbstractAction {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                int offset = textPane.getSelectionStart();
                Document sd=textPane.getDocument();
                String value = getClipboard();
                sd.remove(textPane.getSelectionStart(), textPane.getSelectionEnd()-textPane.getSelectionStart());
                textPane.getDocument().insertString(offset, value , null);
                if (value != null) {
                    textPane.setCaretPosition(offset + value.length());
                }
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }

}

並使用此代碼從剪貼板中獲取純文本,

public String getClipboard() throws ClassNotFoundException, UnsupportedFlavorException {
    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    DataFlavor htmlStringFlavor = new DataFlavor("text/plain; class=java.lang.String");
    try {
        if (t != null && t.isDataFlavorSupported(htmlStringFlavor)) {
            String text = (String) t.getTransferData(htmlStringFlavor);
            return text;
        }
    } catch (UnsupportedFlavorException e) {
    } catch (IOException e) {
    }
    return null;
}

如果您有菜單項,工具欄或其他觸發器,請不要忘記將“粘貼”操作綁定到它們。

我建議您從開始:

    editorKit = new HTMLEditorKit();
    setEditorKit(editorKit);

    htmlDoc = (HTMLDocument) editorKit.createDefaultDocument();
    htmlDoc.setPreservesUnknownTags(false);

然后,您可以使用:

    DataFlavor htmlFlavor = new DataFlavor("text/html;class=java.lang.String");

    String html = (String) clipboard.getData(htmlFlavor);
    editorKit.read(new StringReader(html), htmlDoc, 0);

我把剩下的交給自己。 但是我真的建議您在使用HTML時使用JSoup。 它非常輕,非常強大且非常有用!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM