DefaultStyledDocument.styleChanged (stile Style) potrebbe non funzionare in modo tempestivo?
-
03-10-2019 - |
Domanda
Ho riscontrato un problema intermittente con una classe che estende javax.swing.text.DefaultStyledDocument
. Questo documento è stato inviato a una stampante. Il più delle volte la formattazione del documento è corretto, ma una volta ogni tanto non è così. Sembra che alcuni dei cambiamenti nella formattazione non sono state applicate.
Ho preso uno sguardo al codice di 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();
}
}
}
Il fatto che SwingUtilities.invokeLater(updateRunnable)
si chiama, piuttosto che invokeAndWait(updateRunnable)
, vuol dire che non posso contare sulle mie modifiche di formattazione che compaiono nel documento prima del rendering?
Se questo è il caso, c'è un modo per assicurarsi che io non procedere con il rendering fino a quando si sono verificati gli aggiornamenti?
Soluzione
Si vede un fireChangedUpdate(dde);
alla fine del codice. Provare per aggiungere te stesso come un DocumentListener
. All'interno del metodo DocumentListener.changedUpdate
si dovrebbe essere Salva per stampare il documento con tutte le modifiche incluse.
Altri suggerimenti
Ho avuto simile problema.
Per resolv, ho avvia dopo qualcosa insieme in un testo swing, un invokeLater vuoto, e quando questo invokeLater è fatto, spero che il testo altalena invoke tardi è fatto.
Il mio codice è forse meglio che il mio inglese:
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.
}
});
E 'horribel, ma di lavoro, mi spiace.