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

📄 icon.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 4 页
字号:
<blockquote><pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;!-- JNLP File for DragPictureDemo --&gt;&lt;jnlp  spec="1.0+"  codebase="http://java.sun.com/docs/books/tutorialJWS/src/uiswing/misc/examples"  href="DragPictureDemo.jnlp"&gt;  &lt;information&gt;    &lt;title&gt;DragPictureDemo&lt;/title&gt;    &lt;vendor&gt;The Java(tm) Tutorial: Sun Microsystems, Inc.&lt;/vendor&gt;    &lt;homepage href="http://java.sun.com/docs/books/tutorial/uiswing/misc/examples/index.html#DragPictureDemo"/&gt;    &lt;description&gt;DragPictureDemo&lt;/description&gt;    &lt;description kind="short"&gt;A demo showing how to install        data transfer on a custom component.&lt;/description&gt;    &lt;offline-allowed/&gt;  &lt;/information&gt;  &lt;resources&gt;    &lt;j2se version="1.4"/&gt;    <b>&lt;jar href="allClasses.jar"/&gt;</b>    <b>&lt;jar href="images.jar"/&gt;</b>  &lt;/resources&gt;  &lt;application-desc main-class="DragPictureDemo"/&gt;&lt;/jnlp&gt;</pre></blockquote>    <p>In this example, the class files and the images files     are in separate JAR files. The JAR files are specified     using the XML <code>jar</code> tag.     <p><li>Setting the <code>CLASSPATH</code> environment variable.     This last approach is <em>not recommended</em>.    If <code>CLASSPATH</code> is not set, the current directory (".")    followed by the location of the system classes shipped    with the JRE are used by default.</ul><p>Most of our examples put the images in an <code>images</code>directory under the directory that contains theexamples' class files.  When we createJAR files for the examples, we keep the same relative locations,although often we put the class files in a different JAR filethan the image JAR file.  No matter where the class and image files are in the file system &#151; in one JAR file, or in multipleJAR files, in a named package, or in the default package &#151;the same code finds the image files using<code>getResource</code>.For more information, see<a class="OutsideLink" target="_blank" href="http://java.sun.com/j2se/1.4.2/docs/guide/resources/resources.html">Accessing Resources in a Location-Independent Manner</a> and the<a class="OutsideLink" target="_blank" href="http://java.sun.com/j2se/1.4.2/docs/guide/jws/developersguide/development.html">Application Development Considerations</a>.</blockquote><a name=applet><h3>Loading Images Into Applets</h3></a><blockquote><p>Applets generally load image datafrom the computer that served up the applet.There are two reasons for this. First, untrusted applets can't read from the file systemon which they're running.Second, it just makes sense to put an applet'sclass and data files together on the server.<p>The <code>IconDemoApplet</code> program initializeseach of its image icons from GIF fileswhose locations are specified with URLs.Because <code>IconDemoApplet</code> is designed to bean untrusted applet,we must place the image files under the applet's code base(the server directory containing the applet's class files).The following figure shows the locations offiles for <code>IconDemoApplet</code>.<p><center><IMG SRC="../../figures/uiswing/components/setup.gif" WIDTH="413" HEIGHT="173" ALIGN="BOTTOM" ALT=""></center></p><h4><font color=red>[PENDING: New figure forthcoming.  The newfigure will have box removed from around the text "code base" and "imagedirectory (specified by <code>IMAGEDIR</code> parameter)". The following text replaces the previous comment:"The image files or image directory can be deleted if the appletloads image files from a JAR file."]</font></h4><p>The <code>APPLET</code> tag is where youspecify information about the images used in the applet. For example, here's part of the tag for<a href=IconDemoApplet.atag>IconDemoApplet</a>:<blockquote><pre>&lt;applet code="IconDemoApplet.class"        codebase="examples/"        archive="iconAppletClasses.jar,                 iconStartupImages.jar,                 iconAppletImages.jar"        width="400" height="360"&gt;    &lt;param NAME="IMAGEDIR" VALUE="images"&gt;    &lt;param NAME="IMAGE0" VALUE="stickerface.gif"&gt;    &lt;param NAME="CAPTION0" VALUE="Sticker Face"&gt;    &lt;param NAME="WIDTH0" VALUE="230"&gt;    &lt;param NAME="HEIGHT0" VALUE="238"&gt;    ...&lt;/applet&gt;</pre></blockquote><p>The <code>IMAGEDIR</code> parameter indicatesthat the image files should be in a directory named<code>images</code> relative to the applet's code base.Applets generally use a URL that is constructedrelative to the applet's code base.<p>As you can see from the <code>archive</code>attribute of the preceding <code>APPLET</code> tag,we have deployed IconDemoApplet usingthree JAR files. The classes are in one JAR file,the images required for starting up the UI (thearrow images) are in another JAR file, and therest of the images are in a third JAR file. Separatingthe UI images from the other images means a quickerstart-up time.<p>For more information on specifying JAR fileswith the <code>APPLET</code> tag, see <a class="TutorialLink" target="_top" href="../../deployment/applet/html.html">Using the APPLET Tag	</a> and the<a class="OutsideLink" target="_blank" href="http://java.sun.com/j2se/1.4.2/docs/guide/jar/jarGuide.html">JAR File Overview</a>.<p>When using Java Web Start to deploy an applet,you can use the same approach for loadingresources as you do for applications &#151; the <code>getResource</code> method.However, for applets deployed using Java Plug-in,<code>getResourceAsStream</code> is more efficientfor loading images.<blockquote><hr><strong>Version note:</strong>&nbsp;Prior to release 1.4, when called from an appletdeployed using Java Plug-in, <code>getResource</code> did not lookin JAR files for resources, it looked only in the code base.In this situation, you must either put the images in thecode base, or you must use <code>getResourceAsStream</code>.<hr></blockquote>Here is the code from IconDemoAppletthat reads the images using <code>getResourceAsStream</code>:<blockquote><pre>public class IconDemoApplet extends JApplet ... {    protected String leftButtonFilename = "images/left.gif";    ...    public void init() {        ...        ImageIcon leftButtonIcon = createAppletImageIcon(leftButtonFilename,                                                   "an arrow pointing left");        ...    }    ...    //Returns an ImageIcon, or null if the path was invalid.    //When running an applet using Java Plug-in,    //getResourceAsStream is more efficient than getResource.    protected static ImageIcon createAppletImageIcon(String path,                                              String description) {        int MAX_IMAGE_SIZE = 75000; //Change this to the size of                                    //your biggest image, in bytes.        int count = 0;        BufferedInputStream imgStream = new BufferedInputStream(           IconDemoApplet.class.getResourceAsStream(path));        if (imgStream != null) {            byte buf[] = new byte[MAX_IMAGE_SIZE];            try {                count = imgStream.read(buf);            } catch (IOException ieo) {                System.err.println("Couldn't read stream from file: " + path);            }            try {                imgStream.close();            } catch (IOException ieo) {                 System.err.println("Can't close file " + path);            }            if (count <= 0) {                System.err.println("Empty file: " + path);                return null;            }            return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf),                                 description);        } else {            System.err.println("Couldn't find file: " + path);            return null;        }    }    ...}</pre></blockquote>You might want to copy the <code>createAppletImageIcon</code> methodfor use in your applet. Be sure to change the<code>IconDemoApplet</code> string in the call to<code>getResourceAsStream</code> to the name of your applet.</blockquote><a name=efficiency><h3>Improving Perceived Performance When Loading Image Icons</h3></a><blockquote>Because the photograph images are large,<code>IconDemoApplet</code> uses several techniques to improve theperformance of the program as perceived by the user.<ul><li> <strong>Providing dimmed icons</strong>     &#151; the applet provides dimmed versions of the arrows     for the buttons:<blockquote><pre>imagedir = getParameter("IMAGEDIR");if (imagedir != null)    imagedir = imagedir + "/";...ImageIcon dimmedNextIcon = createAppletImageIcon(    "images/dimmedRight.gif", "a dimmed right arrow");ImageIcon dimmedPreviousIcon = createAppletImageIcon(    "images/dimmedLeft.gif", "a dimmed left arrow");...nextButton.setDisabledIcon(dimmedNextIcon);...previousButton.setDisabledIcon(dimmedPreviousIcon);</pre></blockquote>Without this code,the dimmed versions of the arrows would be computed,which causes a slight delay the first time each button is dimmed.Basically, this technique tradesa noticeable delay when the user clicks the buttons fora smaller, less noticeable delay in the <code>init</code> method.An alternative would be to load the dimmed icons in a backgroundthread after the GUI has been created and shown.<p>This applet uses four separate image filesjust to display arrows on two buttons.The performance impact of these little images can add up,especially if the browser in which the applet is runninguses a separate HTTP connection to load each one.A faster alternative is to implement acustom <code>Icon</code> that paints the arrows.See <a href=#custom>Creating a Custom Icon Implementation</a>for an example.<p>        <li> <strong>Lazy image loading</strong>     &#151; the applet's initialization codeloads only the first photograph.Each other photograph gets loaded when the userfirst requests to see it.By loading images if and when needed,the applet avoids a long initialization.The downside is that the user has to waitto see each photograph.We try to make this wait less noticeableby providing feedback about the image loadingand allowing the user to use the GUIwhile the image is loading.<p>Not all programs can benefit from lazy loading.For example, the<a class="SourceLink" target="_blank" href="../components/examples/TumbleItem.java"><code>TumbleItem.java</code></a> appletperforms an animation, and all of the imagesin the animation are needed up-front.That applet's initialization codecauses the images to be loaded in a background thread,so that the applet can present a GUI (a "Loading Images..." label)before the images have loaded.<p><li> <strong>Background image loading</strong>&#151; the applet uses a<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html">javax.swing.SwingWorker</a>objectto load each photograph image in a background thread.Because the image is loaded in a separate thread, the applet does not freeze up while the image is loading.<p>Here's the code to load each image:<blockquote><pre>private void loadImage(final String imagePath, final int index) {    (new SwingWorker&lt;ImageIcon, Object&gt;() {        public ImageIcon doInBackground() {            return createAppletImageIcon(imagePath,                 "photo #" + index);        }        //Runs on the event-dispatching thread.        public void done() {             Photo photo = photos.elementAt(index);            try {                photo.icon = 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);            }            if (index == current) {                updatePhotograph(photo);            }        }    }).execute();}</pre></blockquote>The <code>doInBackground</code> method,which creates the image icon for the photograph,is invoked by the background thread.After the image icon is fully loaded,the <code>done</code> method is invokedon the event-dispatching thread.This updates the GUI to display the photograph.<p><li> <strong>Status updates</strong>&#151;  while the image is loading inthe background,the applet displays a status message:<blockquote><pre>photographLabel.setIcon(null);photographLabel.setText("Loading image...");</pre></blockquote>This lets the user know that the program is doing something.After the image is loaded,the applet displays the photograph in the viewing area.<p><li> <strong>Caching</strong>&#151;  after each photograph is viewed for the firsttime, the applet caches the image icon for later use. Thus if the user revisits a photograph,the program can use the same image icon anddisplay the photograph quickly.<p>If you write a program without caching image icons,it may appear that some implicit image cachingis going on within the Java platform.However, this is a side effect of the implementationand is not guaranteed.If your program uses one image in many places in its GUI,you can create the image icon onceand use the same instance multiple times.</ul>As with all performance-related issues,these techniques are applicable in some situations and not others.These are not general recommendations for all programs,but some techniques you can try to improve the user's experience.Furthermore,the techniques described hereare designed to improvethe program's perceived performance,but don't necessarily impact its real performance.</blockquote><h3><a name=custom>Creating a Custom Icon Implementation</a></h3><blockquote>If an image differs depending on the state of the component it's within,consider implementing a custom <code>Icon</code> class to paint the image.The really nice thing about a custom iconis that you can easily change the icon's appearanceto reflect its host component's state.<p>Look-and-feel implementations often use custom icons.For example, the Java look and feel uses a single<code>MetalCheckBoxIcon</code> objectto paint all of the check boxes in the GUI.The <code>MetalCheckBoxIcon</code>paints itself differentlydepending on whether its host componentis enabled, pressed, or selected.<p>In this section, we'llconvert a program called <code>ButtonDemo</code>so that it uses a custom icon to paint these two arrows:<blockquote>

⌨️ 快捷键说明

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