【问题标题】:DefaultStyledDocument.styleChanged(Style style) may not run in a timely manner?DefaultStyledDocument.styleChanged(Style style) 可能无法及时运行?
【发布时间】:2023-03-31 05:07:01
【问题描述】:

我遇到了一个扩展 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)这一事实是否意味着我不能指望在文档呈现之前出现在文档中的格式更改?

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我也遇到过类似的问题。

      为了解决,我在swing text中设置了一些东西后启动,一个空的invokeLater,当这个invokeLater完成后,我希望swing text invoke later完成。

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

      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.
        }
      });
      

      这太可怕了,但它的工作,对不起。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-29
        • 2015-04-30
        • 2018-12-03
        • 1970-01-01
        • 1970-01-01
        • 2022-09-29
        • 2018-01-29
        相关资源
        最近更新 更多