⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 applet.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<li> You set the layout manager on a Swing applet's content pane,     not directly on the applet.<li> The default layout manager for a Swing applet's content pane is     <code>BorderLayout</code>.     This differs from the default layout manager for     <code>Applet</code>, which is <code>FlowLayout</code>.<li> You should not put painting code directly in a <code>JApplet</code>     object.     See <a class="TutorialLink" target="_top" href="../painting/index.html">Performing Custom Painting</a>     for examples of how to perform custom painting in applets.</ul></blockquote><h3><a name="thread">Threads in Applets</a></h3><blockquote>Swing components should be created, queried, and manipulatedon the event-dispatching thread,but browsers don't invoke applet "milestone" methodsfrom that thread.For this reason,the milestone methods &#151;<code>init</code>,<code>start</code>,<code>stop</code>,and <code>destroy</code> &#151;should use the <code>SwingUtilities</code> method<code>invokeAndWait</code>(or, if appropriate, <code>invokeLater</code>)so that code that refers to the Swing componentsis executed on the event-dispatching thread.More information about these methods and the event-dispatching threadis in <a class="TutorialLink" target="_top" href="../concurrency/index.html">Concurrency in Swing</a>.<p>Here is an example of an <code>init</code> method:<blockquote><pre>public void init() {    //Execute a job on the event-dispatching thread:    //creating this applet's GUI.    try {        javax.swing.SwingUtilities.invokeAndWait(new Runnable() {            public void run() {                createGUI();            }        });    } catch (Exception e) {        System.err.println("createGUI didn't successfully complete");    }}private void createGUI() {    JLabel label = new JLabel(                       "You are successfully running a Swing applet!");    label.setHorizontalAlignment(JLabel.CENTER);    label.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.black));    getContentPane().add(label, BorderLayout.CENTER);}</pre></blockquote><p>The <code>invokeLater</code> method is not appropriate for this implementationbecause it allows <code>init</code>to return before initialization is complete,which can cause applet problemsthat are difficult to debug.<p>The <code>init</code> method in <code>TumbleItem</code>is more complex, as thefollowing code shows.Like the first example, this <code>init</code> method implementationuses <code>SwingUtilities.invokeAndWait</code>to execute the GUI creation code on the event-dispatching thread.This <code>init</code> methodsets up a<a class="TutorialLink" target="_top" href="../misc/timer.html">Swing timer</a>to fire action events the update the animation.Also, <code>init</code> uses<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html"><code>javax.swing.SwingWorker</code></a> to create a background taskthat loads the animation image files,letting the applet present a GUIright away, without waiting for all resources to be loaded.<blockquote><pre>private void createGUI() {    ...    animator = new Animator();    animator.setOpaque(true);    animator.setBackground(Color.white);    setContentPane(animator);    ...}public void init() {    loadAppletParameters();    //Execute a job on the event-dispatching thread:    //creating this applet's GUI.    try {        <b>javax.swing.SwingUtilities.invokeAndWait(new Runnable() {            public void run() {                createGUI();            }        });</b>    } catch (Exception e) {         System.err.println("createGUI didn't successfully complete");    }    //Set up the timer that will perform the animation.    timer = new javax.swing.Timer(speed, this);    timer.setInitialDelay(pause);    timer.setCoalesce(false);    timer.start(); //Start the animation.    //Background task for loading images.    SwingWorker worker = (new SwingWorker<ImageIcon[], Object>() {            public ImageIcon[] doInBackground() {                final ImageIcon[] innerImgs = new ImageIcon[nimgs];            <em>...//Load all the images...</em>            return imgs;        }        public void done() {            //Remove the "Loading images" label.            animator.removeAll();            loopslot = -1;            try {                imgs = get();            } <em>...//Handle possible exceptions</em>        }    }).execute();}</pre></blockquote><p>You can find the applet's source code in<a class="SourceLink" target="_blank" href="examples/TumbleItem.java"><code>TumbleItem.java</code></a>.To find all the files required for the applet,including a link to a JNLP filethat lets you run it using Java Web Start, see the<a href="examples/index.html#TumbleItem">example index</a>.</blockquote><h3><a name="images">Using Images in a Swing Applet</a></h3><blockquote>The <code>Applet</code> class provides the<code>getImage</code> method forloading images into an applet.The <code>getImage</code> method createsand returns an <code>Image</code> objectthat represents the loaded image.Because Swing components use <code>Icon</code>srather than <code>Image</code>s to refer to pictures,Swing applets tend not to use <code>getImage</code>.Instead Swing applets create instances of<code>ImageIcon</code> &#151; an icon loaded from an image file.<code>ImageIcon</code> comes with a code-saving benefit:it handles image tracking automatically.Refer to <a class="TutorialLink" target="_top" href="../components/icon.html">How to Use Icons</a> for more information.<p>The animation of Duke doing cartwheelsrequires 17 different pictures.The applet uses one <code>ImageIcon</code> per pictureand loads them in its <code>init</code> method.Because images can take a long time to load,the icons are loaded in a separate threadimplemented by a <code>SwingWorker</code> object.Here's the code:<blockquote><pre>public void init() {    ...    imgs = new ImageIcon[nimgs];    (new SwingWorker<ImageIcon[], Object>() {        public ImageIcon[] doInBackground() {            //Images are numbered 1 to nimgs,            //but fill array from 0 to nimgs-1.            for (int i = 0; i &lt; nimgs; i++) {                imgs[i] = loadImage(i+1);            }            return imgs;        }        ...    }).execute();}...protected ImageIcon loadImage(int imageNum) {    String path = dir + "/T" + imageNum + ".gif";    int MAX_IMAGE_SIZE = 2400;  //Change this to the size of                                 //your biggest image, in bytes.    int count = 0;    BufferedInputStream imgStream = new BufferedInputStream(       this.getClass().getResourceAsStream(path));    if (imgStream != null) {        byte buf[] = new byte[MAX_IMAGE_SIZE];        try {            count = imgStream.read(buf);            imgStream.close();        } catch (java.io.IOException ioe) {            System.err.println("Couldn't read stream from file: " + path);            return null;        }        if (count &lt;= 0) {            System.err.println("Empty file: " + path);            return null;        }        return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));    } else {        System.err.println("Couldn't find file: " + path);        return null;    }}</pre></blockquote>The <code>loadImage</code> methodloads the image for the specified frame of animation.It usesthe <code>getResourceAsStream</code> methodrather than the usual <code>getResource</code> methodto get the images.The resulting code isn't pretty,but <code>getResourceAsStream</code>is more efficient than <code>getResource</code>for loading images from JAR files into applets that are executedusing Java Plug-in<sup><font size=-2>TM</font></sup> software.For further details, see<a class="TutorialLink" target="_top" href="../components/icon.html#applet">Loading Images Into Applets</a>.</blockquote><h3><a name="plugin">Embedding an Applet in an HTML Page</a></h3><blockquote>The recommended way to include an applet in an HTML page isusing the APPLET tag.Here's the APPLET tag for the cartwheeling Duke applet:<blockquote><pre>&lt;applet code="TumbleItem.class"         codebase="examples/"        archive="tumbleClasses.jar, tumbleImages.jar"        width="600" height="95"&gt;    &lt;param name="maxwidth" value="120"&gt;    &lt;param name="nimgs" value="17"&gt;    &lt;param name="offset" value="-57"&gt;    &lt;param name="img" value="images/tumble"&gt;Your browser is completely ignoring the &amp;lt;APPLET&amp;gt; tag!&lt;/applet></pre></blockquote>To find out about the various &lt;APPLET&gt; tag parameters, refer to<a class="TutorialLink" target="_top" href="../../deployment/applet/applettag.html">Using the applet Tag</a> and <a class="TutorialLink" target="_top" href="../../deployment/applet/html.html">Using the APPLET Tag	</a>.</blockquote><h3><a name="api">The JApplet API</a></h3><blockquote>The next table lists the interesting methodsthat <code>JApplet</code> adds to the applet API.They give you access to features provided by the root pane.Other methods you might use are defined by the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/Component.html"><code>Component</code></a> and<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/applet/Applet.html"><code>Applet</code></a> classes.See <a href="jcomponent.html#complookapi">Component Methods</a>for a list of commonly used <code>Component</code> methods,and<a class="TutorialLink" target="_top" href="../../deployment/applet/index.html">Applets</a> for help in using <code>Applet</code> methods.<p><table border=1><tr><th align=left>Method</th><th align=left>Purpose</th></tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#setContentPane(java.awt.Container)">void setContentPane(Container)</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#getContentPane()">Container getContentPane()</a>    </td>    <td>Set or get the applet's content pane.        The content pane contains the applet's visible GUI components        and should be opaque.    </td>  </tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#createRootPane()">JRootPane createRootPane()</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#setRootPane(javax.swing.JRootPane)">void setRootPane(JRootPane)</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#getRootPane()">JRootPane getRootPane()</a>    </td>    <td>Create, set, or get the applet's root pane. The root pane        manages the interior of the applet including the content pane,        the glass pane, and so on.     </td>  </tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#setJMenuBar(javax.swing.JMenuBar)">void setJMenuBar(JMenuBar)</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#getJMenuBar()">JMenuBar getJMenuBar()</a>    </td>    <td>Set or get the applet's menu bar        to manage a set of menus for the applet.     </td>  </tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#setGlassPane(java.awt.Component)">void setGlassPane(Component)</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#getGlassPane()">Component getGlassPane()</a>    </td>    <td>Set or get the applet's glass pane.        You can use the glass pane to intercept mouse events.    </td>  </tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#setLayeredPane(javax.swing.JLayeredPane)">void setLayeredPane(JLayeredPane)</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html#getLayeredPane()">JLayeredPane getLayeredPane()</a>    </td>    <td>Set or get the applet's layered pane.        You can use the applet's layered pane to put components on top of        or behind other components.    </td>  </tr></table></blockquote><h3><a name="eg">Applet Examples</a></h3><blockquote>This table shows examples of Swing appletsand where those examples are described.<p><table><tr><th align=left> Example</th><th align=left> Where Described</th><th align=left> Notes</th></tr><tr><td> <a href="examples/index.html#TumbleItem">     <code>TumbleItem</code></a></td><td> This page</td><td> An animation applet</td></tr><tr><td> <a href="../components/examples/index.html#IconDemoApplet">     <code>IconDemoApplet</code></a></td><td> <a class="TutorialLink" target="_top" href="../components/icon.html">How to Use Icons</a></td><td> An applet for showing photos.</td></tr></table>        </blockquote>        <div class=NavBit>            <a target=_top href=componentlist.html>&laquo; Previous</a>            &bull;            <a target=_top href=../TOC.html>Trail</a>            &bull;            <a target=_top href=button.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> How to Use Various Components        <br><b>Next page:</b> How to Use Buttons, Check Boxes, and Radio Buttons    </div>    </body></html> 

⌨️ 快捷键说明

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