Note that there are some explanatory texts on larger screens.

plurals
  1. POClever asynchronous repaint in Java
    text
    copied!<p>I have a use-case coming from a GUI problem I would like to submit to your sagacity. </p> <p><strong>Use case</strong></p> <p>I have a GUI that displays a computation result depending on some parameters the user set in a GUI. For instance, when the user moves a slider, several events are fired, that all trigger a new computation. When the user adjust the slider value from A to B, a dozens of events are fired.</p> <p>But the computation can take up to several seconds, whereas the slider adjustment can fire an event every few 100 ms.</p> <p>How to write a proper Thread that would listen to these events, and kind of filter them so that the repaint of the results is lively? Ideally you would like something like</p> <ul> <li>start a new computation as soon as first change event is received;</li> <li>cancel the first computation if a new event is received, and start a new one with the new parameters;</li> <li>but ensure that the last event will not be lost, because the last completed computation needs to be the one with last updated parameters. </li> </ul> <p><strong>What I have tried</strong></p> <p>A friend of mine (A. Cardona) proposed this low level approach of an Updater thread that prevents too many events to trigger a computation. I copy-paste it here (GPL):</p> <p>He puts this in a class that extends Thread:</p> <pre class="lang-java prettyprint-override"><code>public void doUpdate() { if (isInterrupted()) return; synchronized (this) { request++; notify(); } } public void quit() { interrupt(); synchronized (this) { notify(); } } public void run() { while (!isInterrupted()) { try { final long r; synchronized (this) { r = request; } // Call refreshable update from this thread if (r &gt; 0) refresh(); // Will trigger re-computation synchronized (this) { if (r == request) { request = 0; // reset wait(); } // else loop through to update again } } catch (Exception e) { e.printStackTrace(); } } } public void refresh() { // Execute computation and paint it ... } </code></pre> <p>Every-time an event is sent by the GUI stating that parameters have been changed, we call <code>updater.doUpdate()</code>. This causes the method <code>refresh()</code> to be called much less. But I have no control on this.</p> <p><strong>Another way?</strong></p> <p>I was wondering if there is another way to do that, that would use the jaca.concurrent classes. But I could not sort in the Executors framework what would be the one I should start with.</p> <p>Does any of you have some experience with a similar use case? </p> <p>Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload