У меня есть класс, который использует следующий код для копирования всего текста из 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);
}
person
ManEatingCheese
schedule
15.06.2013