繁体   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