DefaultStyledDocument.styleChanged(样式样式)可能无法及时运行?

时间:2010-05-06 20:52:51

标签: java swing defaultstyleddocument javax.swing.text swingutilities

我遇到了一个延长javax.swing.text.DefaultStyledDocument的课程的间歇性问题。此文档正在发送到打印机。大多数情况下,文档的格式看起来是正确的,但偶尔也没有。看起来格式化中的某些更改尚未应用。

我看了DefaultStyledDocument.styleChanged(Style style)代码:

/**
 * Called when any of this document's styles have changed.
 * Subclasses may wish to be intelligent about what gets damaged.
 *
 * @param style The Style that has changed.
 */
protected void styleChanged(Style style) {
    // Only propagate change updated if have content
    if (getLength() != 0) {
        // lazily create a ChangeUpdateRunnable
        if (updateRunnable == null) {
            updateRunnable = new ChangeUpdateRunnable();
        }

        // We may get a whole batch of these at once, so only
        // queue the runnable if it is not already pending
        synchronized(updateRunnable) {
            if (!updateRunnable.isPending) {
                SwingUtilities.invokeLater(updateRunnable);
                updateRunnable.isPending = true;
            }
        }
    }
}

/**
 * When run this creates a change event for the complete document
 * and fires it.
 */
class ChangeUpdateRunnable implements Runnable {
    boolean isPending = false;

public void run() {
        synchronized(this) {
            isPending = false;
        }

    try {
    writeLock();
    DefaultDocumentEvent dde = new DefaultDocumentEvent(0,
                      getLength(),
                      DocumentEvent.EventType.CHANGE);
    dde.end();
    fireChangedUpdate(dde);
    } finally {
    writeUnlock();
    }
}
}

调用SwingUtilities.invokeLater(updateRunnable)而不是invokeAndWait(updateRunnable)这一事实是否意味着我无法指望文档在呈现之前出现的格式更改?

如果是这种情况,有没有办法确保在更新发生之前我不进行渲染?

2 个答案:

答案 0 :(得分:2)

您会在代码末尾看到fireChangedUpdate(dde);。尝试将自己添加为DocumentListener。在DocumentListener.changedUpdate方法中,您应该保存以打印包含所有更改的文档。

答案 1 :(得分:1)

我遇到过类似的问题。

要解析,我在设置了一个swing文本,一个空的invokeLater之后启动,并且当这个invokeLater完成时,我希望稍后调用的swing文本完成。

我的代码可能比我的英文好:

doc.formatSomethingWhichPerhapsLaunchInvokeLater();
EventQueue.invokeLater(new java.lang.Runnable()
{
  public void run()
  {
    // at this point, I hope all swing text stuff is finish. 
    // Until now, it's the case.
  }
});

这是可怕的,但这很有用,抱歉。