1

我使用 JEditorPane 作为“橡皮图章”将 HTML 文本呈现为 PDF。我需要文本以特定宽度换行,并且需要在文本后面应用白色“突出显示”。因此,我在 PDF 渲染线程中创建了一个 JEditorPane,设置了文本和样式表,然后将其绘制到 PDF 图形中。但是,我在 HTML 编辑器工具包的深处遇到了间歇性的 NullPointerException。这可以通过此 SSCCE 重现:

import javax.swing.*;
import javax.swing.text.View;
import javax.swing.text.html.HTMLDocument;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * @author sbarnum
 */
public class TextMarkerUtilsTest {
    public static void main(String[] args) throws Exception {
        Rectangle bounds = new Rectangle(255, 255);
        BufferedImage image = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D d = image.createGraphics();
        d.setClip(bounds);
        for (int i=0; i<1000; i++) {
            JEditorPane renderHelper = new JEditorPane("text/html", "<html><body>This is my text.</body></html>");
            HTMLDocument document = (HTMLDocument) renderHelper.getDocument();
            document.getStyleSheet().addRule("foo{color:black;}");
            View rootView = renderHelper.getUI().getRootView(renderHelper);
            rootView.paint(d, bounds);
        }
    }

}

运行上面的代码会抛出以下异常,通常在循环几次之后:

java.lang.NullPointerException
    at sun.font.FontDesignMetrics$MetricsKey.init(FontDesignMetrics.java:199)
    at sun.font.FontDesignMetrics.getMetrics(FontDesignMetrics.java:267)
    at sun.swing.SwingUtilities2.getFontMetrics(SwingUtilities2.java:949)
    at javax.swing.JComponent.getFontMetrics(JComponent.java:1599)
    at javax.swing.text.LabelView.getFontMetrics(LabelView.java:154)
    at javax.swing.text.html.InlineView.calculateLongestWordSpanUseWhitespace(InlineView.java:246)
    at javax.swing.text.html.InlineView.calculateLongestWordSpan(InlineView.java:191)
    at javax.swing.text.html.InlineView.getLongestWordSpan(InlineView.java:177)
    at javax.swing.text.html.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:140)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:918)
    at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:551)
    at javax.swing.text.html.ParagraphView.getMinimumSpan(ParagraphView.java:261)
    at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:886)
    at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:129)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:918)
    at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:551)
    at javax.swing.text.html.BlockView.getMinimumSpan(BlockView.java:361)
    at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:886)
    at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:129)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:918)
    at javax.swing.text.BoxView.setSpanOnAxis(BoxView.java:326)
    at javax.swing.text.BoxView.layout(BoxView.java:691)
    at javax.swing.text.BoxView.setSize(BoxView.java:380)
    at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1703)
    at javax.swing.plaf.basic.BasicTextUI$RootView.paint(BasicTextUI.java:1422)
    at com.prosc.msi.model.editor.TextMarkerUtilsTest$1.run(TextMarkerUtilsTest.java:40)
    at java.lang.Thread.run(Thread.java:680)

一些有趣的发现:

  • 如果以上在 Event Dispatch Thread 中运行,它可以工作
  • 如果我调用addRule("foo{color:black;}"),它可以工作(我需要指定规则,但规则是什么似乎并不重要,如果添加任何规则,它就会失败)

问题出在javax.swing.text.GlyphPainter1.sync()哪里javax.swing.text.GlyphView.getFont(),返回 null。通过设置条件断点,我看到GlyphView在这种情况下是一个javax.swing.text.html.InlineView. 在断点停止后调用getFont()会返回一个非空字体,因此没有及时初始化某些内容。

我意识到摆动组件不是线程安全的,但是我不应该能够在后台线程中实例化 JEditorPane 并在该后台线程中安全地操作它,只要只有一个线程正在调用组件吗?

4

2 回答 2

1

由于您仅使用轻量级组件,因此可以选择无头模式。您可以使用 将工作排除在 GUI 的 EDT 之外ProcessBuilder,如图所示

public static void main(String[] args) throws Exception {
    System.setProperty("java.awt.headless", "true"); 
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            Rectangle bounds = new Rectangle(255, 255);
            BufferedImage image = new BufferedImage(
                bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB);
            Graphics2D d = image.createGraphics();
            d.setClip(bounds);
            for (int i = 0; i < 1000; i++) {
                JEditorPane renderHelper = new JEditorPane(
                    "text/html", "<html><body>This is my text.</body></html>");
                HTMLDocument document = (HTMLDocument) renderHelper.getDocument();
                document.getStyleSheet().addRule("foo{color:black;}");
                View rootView = renderHelper.getUI().getRootView(renderHelper);
                rootView.paint(d, bounds);
            }
        }
    });
}
于 2012-06-25T23:35:23.723 回答
0

感谢 Marko 建议寻找事件调度线程的回调,我最终在HTMLDocument.styleChanged(). 我的子类:

public class ThreadFriendlyHTMLDocument extends HTMLDocument {
    @Override
    protected void styleChanged(final Style style) {
        // to fix GlyphPainter1.sync NullPointerException, we call this in the current thread, instead of the EDT
        DefaultDocumentEvent dde = new DefaultDocumentEvent(0,
                          this.getLength(),
                          DocumentEvent.EventType.CHANGE);
        dde.end();
        fireChangedUpdate(dde);
    }
}
于 2012-06-26T21:04:30.820 回答