【发布时间】:2009-11-08 11:06:45
【问题描述】:
我正在尝试使用 JTextPane 创建一个所见即所得的编辑器。
我正在使用 DefaultEditorKit.CopyAction 在编辑器中复制文本。但是这种方法不保留文本的样式。有人可以告诉我如何复制 JTextPane 中的文本并保留样式吗?
【问题讨论】:
标签: java swing copy copy-paste jtextpane
我正在尝试使用 JTextPane 创建一个所见即所得的编辑器。
我正在使用 DefaultEditorKit.CopyAction 在编辑器中复制文本。但是这种方法不保留文本的样式。有人可以告诉我如何复制 JTextPane 中的文本并保留样式吗?
【问题讨论】:
标签: java swing copy copy-paste jtextpane
http://java-sl.com/tip_merge_documents.html 你可以使用这个。如果您需要文档的一部分,只需选择所需的源窗格片段。
【讨论】:
我有一个类,它使用以下代码将 StyledDocument 中的所有文本复制到用户的剪贴板中;它似乎保留了颜色、粗体和下划线等属性(尚未用其他任何东西对其进行测试)。请注意,“this.doc”是一个 StyledDocument。
不保证这是最好的方法。
try
{
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
RTFEditorKit rtfek = new RTFEditorKit();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
rtfek.write( baos, this.doc, 0, this.doc.getLength() );
baos.flush();
DataHandler dh = new DataHandler( baos.toByteArray(), rtfek.getContentType() );
clpbrd.setContents(dh, null);
}
catch ( IOException | BadLocationException e )
{
e.printStackTrace();
}
如果你只想复制文档的一小部分,我想你想修改这一行:
rtfek.write( baos, this.doc, int startPosition, int endPosition )
编辑:事实证明,创建 RTFEditorKit 的人决定他们不需要遵守他们的 API。基本上上面的 startPosition 和 endPosition 没有任何作用。
/**
* Write content from a document to the given stream
* in a format appropriate for this kind of content handler.
*
* @param out The stream to write to
* @param doc The source for the write.
* @param pos The location in the document to fetch the
* content.
* @param len The amount to write out.
* @exception IOException on any I/O error
* @exception BadLocationException if pos represents an invalid
* location within the document.
*/
public void write(OutputStream out, Document doc, int pos, int len)
throws IOException, BadLocationException {
// PENDING(prinz) this needs to be fixed to
// use the given document range.
RTFGenerator.writeDocument(doc, out);
}
【讨论】:
图书出版商 Manning 提供免费下载 Matthew Robinson 和 Pavel Vorobiev 的第一版“Swing”,地址为http://www.manning.com/robinson2。 (向下滚动页面,查找“下载完整的 Swing Book (MS Word 97)”链接。)
第 20 章讨论了使用 JTextPane 作为编辑组件的一部分来开发 WYSIWYG RTF 编辑器。新版的书进行了修订,描述了一个所见即所得的HTML编辑器的创建,但它不是免费的。 (尽管链接上的页面显示,新版本的纸质版似乎不可用,但如果您有兴趣,电子书是可用的。)
当我尝试做类似的事情时,这对我来说是一个很好的资源。
【讨论】:
尝试使用序列化。 类似的东西
public static DefaultStyledDocument cloneStyledDoc(DefaultStyledDocument source) {
try {
DefaultStyledDocument retDoc = new DefaultStyledDocument();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(source); // write object to byte stream
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray() );
ObjectInputStream ois = new ObjectInputStream(bis);
retDoc = (DefaultStyledDocument) ois.readObject(); //read object from stream
ois.close();
return retDoc;
}
catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
窥探 Cay Horstmann 的书 http://horstmann.com/corejava.html
【讨论】: