Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It would behoove you to learn about <code>SwingWorker</code> which gives you ultimate flexibility when it comes to threading. Here's the short and skinny:</p> <p>All GUI actions should be on the <code>Event Dispatch Thread</code> (EDT for short). All time-consuming tasks should be on background threads. SwingWorker allows you to control which thread you're running code on.</p> <p>First, to run anything on the EDT, you use this code:</p> <pre><code>SwingUtilities.invokeLater(new Runnable() { @Override public void run() { jLabel1.setText("Yay I'm on the EDT."); } }); </code></pre> <p>But if you want to run a time-consuming task, that won't do what you need. Instead, you'll need a SwingWorker like this:</p> <pre><code>class Task extends SwingWorker&lt;Void, Void&gt; { public Task() { /* * Code placed here will be executed on the EDT. */ jLabel1.setText("Yay I'm on the EDT."); execute(); } @Override protected Void doInBackground() throws Exception { /* * Code run here will be executed on a background, "worker" thread that will not interrupt your EDT * events. Run your time consuming tasks here. * * NOTE: DO NOT run ANY Swing (GUI) code here! Swing is not thread-safe! It causes problems, believe me. */ return null; } @Override protected void done() { /* * All code run in this method is done on the EDT, so keep your code here "short and sweet," i.e., not * time-consuming. */ if (!isCancelled()) { boolean error = false; try { get(); /* All errors will be thrown by this method, so you definitely need it. If you use the Swing * worker to return a value, it's returned here. * (I never return values from SwingWorkers, so I just use it for error checking). */ } catch (ExecutionException | InterruptedException e) { // Handle your error... error = true; } if (!error) { /* * Place your "success" code here, whatever it is. */ } } } } </code></pre> <p>Then you need to launch your SwingWorker with this:</p> <pre><code>new Task(); </code></pre> <p>For more info, check out Oracle's documentation: <a href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html" rel="nofollow">http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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