求助关于用Swing里面的RTFEditorKit读写RTF文档的问题
我在用Swing里面提供的RTFEditorKit做读写RTF文档的操作。读写一切正常,但是字体的颜色一直不对。程序如下:
问题1):设置字体颜色是不是用如下程序
StyleConstants.CharacterConstants.setBackground(attrs, Color.red)
问题2):如下程序这么会把从本段开始以后所有的字体颜色都变过来?
StyleConstants.CharacterConstants.setForeground(attrs, Color.red)
问题3):怎么样可以给一段文字加上删除的符号(就是文字中间有一杠)
谢谢各位高手了,小弟没分,不知道能不能解答。谢谢,问题很紧急。
package com.parser.example;
import org.apache.log4j.Logger;
import javax.swing.text.*;
import javax.swing.text.rtf.RTFEditorKit;
import java.awt.*;
import java.io.*;
/**
* User: Administrator
* Date: 2011-11-4
* Time: 23:18:53
*/
public class RTFReader {
private Logger logger = Logger.getLogger(RTFReader.class);
private RTFEditorKit kit;
private static String testRtfFilePath = "E:/test.rtf";
public RTFReader(final RTFEditorKit kit) {
this.kit = kit;
}
public static void main(String args[]) {
RTFEditorKit kit = new RTFEditorKit();
RTFReader utils = new RTFReader(kit);
Document document = utils.buildDocumentByRTF(testRtfFilePath);
SimpleAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.CharacterConstants.setBackground(attrs, Color.red);//字体颜色是不是这样设置的?
StyleConstants.CharacterConstants.setForeground(attrs, Color.red);//如果用setForeground,字体颜色会设置成功,但是之后的颜色都会变成红色。
utils.insertTextToRTF(0, "Test Text", document, attrs);
utils.writeDocumentToRTF(document, testRtfFilePath);
}
public Document insertTextToRTF(int offset, String text, Document document, AttributeSet attributeSet) {
try {
document.insertString(offset, text, attributeSet);
} catch (BadLocationException e) {
logger.error("Something wrong with updating a RTF document");
}
return document;
}
public Document buildDocumentByRTF(String rtfPath) {
File file = new File(rtfPath);
Document document = kit.createDefaultDocument();
InputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
kit.read(fileInputStream, document, 0);
fileInputStream.close();
} catch (FileNotFoundException e) {
logger.error("The file does not exist");
} catch (IOException e) {
logger.error("Something wrong with reading the file");
} catch (BadLocationException e) {
logger.error("Something wrong with updating a RTF document");
}
return document;
}
public String getDocumentText(Document document) {
String documentText = null;
try {
documentText = document.getText(0, document.getLength());
} catch (BadLocationException e) {
logger.error("Something wrong with updating a RTF document");
}
return documentText;
}
public File writeDocumentToRTF(Document document, String rtfPath) {
File file = new File(rtfPath);
try {
OutputStream outputStream = new FileOutputStream(file);
kit.write(outputStream, document, 0, document.getLength());
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
logger.error("The file does not exist");
} catch (IOException e) {
logger.error("Something wrong with reading the file");
} catch (BadLocationException e) {
logger.error("Something wrong with updating a RTF document");
}
return file;
}
}