这段代码有点有效,但似乎不太理想。有更好的方法吗?此外,在图形上除0,0之外的其他位置渲染文本的好方法是什么?
private static void testRtfRender() {
String s = "{\\rtf1\\ansi\n" +
"{\\fonttbl\\f0\\fnil Monospaced;\\f1\\fnil Lucida Grande;}\n" +
"\n" +
"\\f1\\fs26\\i0\\b0\\cf0 this is a \\b test\\b0\\par\n" +
"}";
JTextPane pane = new JTextPane();
pane.setContentType("text/rtf");
pane.setText(s);
final Dimension preferredSize = pane.getUI().getPreferredSize(pane);
int w = preferredSize.width;
int h = preferredSize.height;
pane.setSize(w, h);
pane.addNotify();
pane.validate();
// would be nice to use this box view instead of instantiating a UI
// however, unless you call setParent() on the view it's useless
// What should the parent of a root element be?
//BoxView view = (BoxView) pane.getEditorKit().getViewFactory().create(pane.getStyledDocument().getDefaultRootElement());
//view.paint(d, new Rectangle(w, h));
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
final Graphics2D d = img.createGraphics();
d.setClip(0, 0, w, h); // throws a NullPointerException if I leave this out
pane.getUI().paint(d, pane);
d.dispose();
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(img)));
}