simple.html

来自「jsf、swing的官方指南」· HTML 代码 · 共 451 行 · 第 1/2 页

HTML
451
字号
                return cookieValue == 'yes';            }        }        return true;    }    function showLeft(b) {        var contents = document.getElementById("LeftBar");        var main = document.getElementById("MainFlow");        var toggle = document.getElementById("ToggleLeft");        if (b) {            contents.className = "LeftBar_shown";            main.className = "MainFlow_indented";            toggle.innerHTML = "Hide the TOC";            document.cookie = 'tutorial_showLeftBar=yes; path=/';        } else {            contents.className = "LeftBar_hidden";            main.className = "MainFlow_wide";            toggle.innerHTML = "Show the TOC";            document.cookie = 'tutorial_showLeftBar=no; path=/';        }    }    function toggleLeft() {        showLeft(document.getElementById("LeftBar").className ==                "LeftBar_hidden");        document.getElementById("ToggleLeft").blur();    }    function load() {        showLeft(leftBar());        document.getElementById("ToggleLeft").style.display="inline";    }    </script>    </head><body onload="load()">    <div id=TopBar> <div id=TopBar_tr> <div id=TopBar_tl> <div id=TopBar_br> <div id=TopBar_bl>                         <div id=TopBar_right>                             <a target="_blank"                                href="http://java.sun.com/javase/6/download.jsp">Download                                the JDK</a>                            <br>                            <a href="../../search.html" target="_blank">Search the                                Tutorials</a>                            <br>                            <a href="javascript:toggleLeft()"                                id="ToggleLeft">Hide the TOC</a>                        </div>                    </div> </div> </div> </div> </div>    <div class=PrintHeaders>        <b>Trail:</b> Creating a GUI with JFC/Swing        <br><b>Lesson:</b> Concurrency in Swing        <br><b>Section:</b> Worker Threads and SwingWorker    </div>    <div id=LeftBar class=LeftBar_shown>        <div id=Contents>            <div class="linkLESSON"><a href="index.html">Concurrency in Swing</a></div><div class="linkAHEAD"><a href="initial.html">Initial Threads</a></div><div class="linkAHEAD"><a href="dispatch.html">The Event Dispatch Thread</a></div><div class="linkAHEAD"><a href="worker.html">Worker Threads and SwingWorker</a></div><div class="nolinkBHEAD">Simple Background Tasks</div><div class="linkBHEAD"><a href="interim.html">Tasks that Have Interim Results</a></div><div class="linkBHEAD"><a href="cancel.html">Canceling Background Tasks</a></div><div class="linkBHEAD"><a href="bound.html">Bound Properties and Status Methods</a></div></div>    </div>    <div id=MainFlow class=MainFlow_indented>            <span id=BreadCrumbs>                <a href=../../index.html target=_top>Home Page</a>                &gt;                <a href=../index.html target=_top>Creating a GUI with JFC/Swing</a>                &gt;                <a href=index.html target=_top>Concurrency in Swing</a>            </span>            <div class=NavBit>                <a target=_top href=worker.html>&laquo;&nbsp;Previous</a>&nbsp;&bull;&nbsp;<a target=_top href=../TOC.html>Trail</a>&nbsp;&bull;&nbsp;<a target=_top href=interim.html>Next&nbsp;&raquo;</a>            </div>            <div id=PageTitle>Simple Background Tasks</div>            <blockquote>Let's start with a task that is very simple, but potentiallytime-consuming. The <a class="SourceLink" target="_blank" href="../components/examples/TumbleItem.java"><code><code>TumbleItem</code></code></a>applet loads a set of graphic files used inan animation. If the graphic files are loaded from aninitial thread, there may be a delay before the GUIappears. If the graphic files are loaded from the event dispatchthread, the GUI may be temporarily unresponsive.<p>To avoid these problems, <code>TumbleItem</code> creates and executesan instance of <code>SwingWorker</code> from its initial threads. Theobject's <code>doInBackground</code> method, executing in a worker thread,loads the images into an <code>ImageIcon</code> array, and returns areference to it.Then the <code>done</code> method, executing in the eventdispatch thread, invokes <code>get</code> to retrieve this reference,which it assigns to to an applet class field named <code>imgs</code>Thisallows <code>TumbleItem</code> to contruct the GUI immediately,without waiting for the images to finish loading.<p>Here is the code that defines and executes the<code>SwingWorker</code> object.<blockquote><pre>SwingWorker worker = new SwingWorker&lt;ImageIcon[], Void&gt;() {    @Override    public ImageIcon[] doInBackground() {        final ImageIcon[] innerImgs = new ImageIcon[nimgs];        for (int i = 0; i &lt; nimgs; i++) {            innerImgs[i] = loadImage(i+1);        }        return innerImgs;    }    @Override    public void done() {        //Remove the "Loading images" label.        animator.removeAll();        loopslot = -1;        try {            imgs = get();        } catch (InterruptedException ignore) {}        catch (java.util.concurrent.ExecutionException e) {            String why = null;            Throwable cause = e.getCause();            if (cause != null) {                why = cause.getMessage();            } else {                why = e.getMessage();            }            System.err.println("Error retrieving file: " + why);        }    }};</pre></blockquote>All concrete subclasses of <code>SwingWorker</code> implement<code>doInBackground</code>; implementation of <code>done</code> isoptional.<p>Notice that <code>SwingWorker</code> is a generic class, with two typeparameters. The first type parameter specifies a return type for<code>doInBackground</code>, and also for the <code>get</code> method,which is invoked by other threads to retrieve the object returned by<code>doInBackground</code>.<code>SwingWorker</code>'s second type parameter specifies a type forinterim results returned while the background task is still active.Since this example doesn't return interim results, <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/lang/Void.html"><code>Void</code> </a>    is used as a placeholder.<p>You may wonder if the code that sets <code>imgs</code> isunnecessarily complicated. Why make <code>doInBackground</code> returnan object and use <code>done</code> to retrieve it? Why not just have<code>doInBackground</code> set <code>imgs</code> directly?  Theproblem is that the object <code>imgs</code> refers to is created inthe worker thread and used in the event dispatch thread. When objectsare shared between threads in this way, you must make sure thatchanges made in one thread are visible to the other. Using<code>get</code> guarantees this, because using <code>get</code>creates a <i>happens before</i> relationship between the code thatcreates <code>imgs</code> and the code that uses it. For more on thehappens before relationship, refer to<a class="TutorialLink" target="_top" href="../../essential/concurrency/memconsist.html">Memory Consistency Errors</a>in the <a class="TutorialLink" target="_top" href="../../essential/concurrency/index.html">Concurrency</a>lesson.<p>There are actually two ways to retrieve the object returned by<code>doInBackground</code>.<ul>    <li>Invoke <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html#get()"><code>SwingWorker.get</code> with no arguments</a>. If the background task is not finished,    <code>get</code> blocks until it is.    <li>Invoke <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html#get(long,%20java.util.concurrent.TimeUnit)"><code>SwingWorker.get</code> with arguments indicating a timeout</a>. If the background task is not finished,    <code>get</code> blocks until it is &mdash; unless the timeout    expires first, in which case <code>get</code> throws    <code>java.util.concurrent.TimeoutException</code>.</ul>Be careful when invoking either overload of <code>get</code> from theevent dispatch thread; until <code>get</code> returns, no GUI eventsare being processed, and the GUI is "frozen".  Don't invoke<code>get</code> without arguments unless you are confident that thebackground task is complete or close to completion.<p>For more on the <code>TumbleItem</code> example, refer to<a class="TutorialLink" target="_top" href="../misc/timer.html">How to Use Swing Timers</a>in the lesson<a class="TutorialLink" target="_top" href="../misc/index.html">Using Other Swing Features</a>.        </blockquote>        <div class=NavBit>            <a target=_top href=worker.html>&laquo; Previous</a>            &bull;            <a target=_top href=../TOC.html>Trail</a>            &bull;            <a target=_top href=interim.html>Next &raquo;</a>        </div>    </div>    <div id=Footer><div id=TagNotes>    Problems with the examples? Try <a target="_blank"        href=../../information/run-examples.html>Compiling and Running        the Examples: FAQs</a>.    <br>    Complaints? Compliments? Suggestions? <a target="_blank"        href="http://developer.sun.com/contact/tutorial_feedback.jsp">Give    us your feedback</a>.<br><br>    <a target="_blank" href="../../information/copyright.html">Copyright</a>    1995-2006 Sun Microsystems, Inc.  All rights reserved.    <span id=Download></span></div>     </div>    <div class=PrintHeaders>        <b>Previous page:</b> Worker Threads and SwingWorker        <br><b>Next page:</b> Tasks that Have Interim Results    </div>    </body></html> 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?