📄 icon.html
字号:
the location of the class <code>LabelDemo</code>, andwill be resolved to an absolute URL. The<code>description</code> argument is a string that allows<a href=../misc/access.html>assistive technologies</a>to help a visually impaired user understand what informationthe icon conveys.<p>Generally, applications provide their own set of images usedas part of the application, as is the case with theimages used by many of our demos. You should usethe <code>Class</code> <code>getResource</code>method to obtain the path to the image.This allows the application toverify that the image is available and to provide sensibleerror handling if it is not. When the image is not partof the application, <code>getResource</code> should not be used andthe <code>ImageIcon</code> constructor is used directly. For example:<blockquote><pre>ImageIcon icon = new ImageIcon("/home/sharonz/images/middle.gif", "a pretty but meaningless splat");</pre></blockquote><p>When you specify a filename or URL to an <code>ImageIcon</code> constructor,processing is blocked until after the image data is completely loadedor the data location has proven to be invalid.If the data location is invalid (but non-null), an<code>ImageIcon</code> is still successfully created;it just has no size and, therefore, paints nothing.As we showed in the <code>createImageIcon</code> method,it's wise to first verify that the URL points to an existing filebefore passing it to the <code>ImageIcon</code> constructor. This allows graceful error handling when the file isn't present.If you want more information while the image is loading,you can register an observeron an image icon by calling its <code>setImageObserver</code> method.<p>Under the covers,each image icon uses an<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/Image.html"><code>Image</code></a> object to hold the image data.<p>The rest of this section covers the following topics:<ul><li><a href=#example>A More Complex Image Icon Example</a><li><a href=#getresource>Loading Images Using getResource</a><li><a href=#applet>Loading Images Into Applets</a><li><a href=#efficiency>Improving Perceived Performance When Loading Image Icons</a><li><a href=#custom>Creating a Custom Icon Implementation</a><li><a href=#api>The Image Icon API</a><li><a href=#eg>Examples that Use Icons</a></ul><a name=example></blockquote><h3>A More Complex Image Icon Example</h3><blockquote>Here's an applet that uses eight image icons.In the snapshot, you can see three of them:one displays the photographand two decorate buttonswith small arrows.<p><center><a href="IconDemoApplet.html" target="_blank"><IMG SRC="../../figures/uiswing/dnd/IconDemoApplet.gif" WIDTH="410" HEIGHT="441" ALIGN="BOTTOM" ALT="Click this figure to run the applet."></a><br><em>This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.</em></center></p><p><h4 align=center><font color=red>[PENDING: New screenshot forthcoming.]</font></h4><p><blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/misc/examples/IconDemoApplet.jnlp">Run IconDemoApplet</a> using <a href=http://java.sun.com/products/javawebstart> Java<sup><font size=-2>TM</font></sup> Web Start</a>. Or, to compile and run the example yourself, consult the <a href="examples/index.html#IconDemoApplet">example index</a>.<li> Click the <strong>Previous Picture</strong>and <strong>Next Picture</strong> buttons to view the photographs.<li> Hold the mouse over a photograph. A tool tip appears that indicates the filename of the current photograph and its width and height.</ol><hr></blockquote><p>IconDemoApplet demonstrates icons used in the following ways:<ul><li>As a GUI element attached to a button (the left and right arrows).<li>As an alternate version of the icon to be used when the button is disabled (dimmed left and right arrows).<li>To display an image (the four photographs).</ul><p>The code that follows creates the four arrow image icons andattaches them to the two buttons. You can find the applet's code in<a class="TutorialLink" target="_top" href="examples/IconDemoApplet.java">IconDemoApplet.java</a>.<blockquote><pre>//Create the next and previous buttons.ImageIcon nextIcon = createAppletImageIcon("images/right.gif", "a right arrow");ImageIcon dimmedNextIcon = createAppletImageIcon("images/dimmedRight.gif", "a dimmed right arrow");ImageIcon previousIcon = createAppletImageIcon("images/left.gif", "a left arrow");ImageIcon dimmedPreviousIcon = createAppletImageIcon("images/dimmedLeft.gif", "a dimmed left arrow");nextButton = new JButton("Next Picture", nextIcon);nextButton.setDisabledIcon(dimmedNextIcon);nextButton.setVerticalTextPosition(AbstractButton.CENTER);nextButton.setHorizontalTextPosition(AbstractButton.LEFT);...previousButton = new JButton("Previous Picture", previousIcon);previousButton.setDisabledIcon(dimmedPreviousIcon);previousButton.setVerticalTextPosition(AbstractButton.CENTER);previousButton.setHorizontalTextPosition(AbstractButton.RIGHT);</pre></blockquote><p>The action handler for the buttonsinitiates loading the photographs into theimage icon:<blockquote><pre>//User clicked either the next or the previous button.public void actionPerformed(ActionEvent e) { //Show loading message. photographLabel.setIcon(null); photographLabel.setText("Loading image..."); //Compute index of photograph to view. if (e.getActionCommand().equals("next")) { current += 1; if (!previousButton.isEnabled()) previousButton.setEnabled(true); if (current == pictures.size() - 1) nextButton.setEnabled(false); } else { current -= 1; if (!nextButton.isEnabled()) nextButton.setEnabled(true); if (current == 0) previousButton.setEnabled(false); } //Get the photo object. Photo pic = (Photo)pictures.elementAt(current); //Update the caption and number labels. captionLabel.setText(pic.caption); numberLabel.setText("Picture " + (current+1) + " of " + pictures.size()); //Update the photograph. ImageIcon icon = pic.getIcon(); if (icon == null) { //haven't viewed this photo before loadImage(imagedir + pic.filename, current); } else { updatePhotograph(current, pic); }}</pre></blockquote><p>The photographs are loaded in a separate thread by the <code>loadImage</code> method — its code isshown a little later in this section.<p>The <code>Photo</code> class, an inner class in<a class="TutorialLink" target="_top" href="examples/IconDemoApplet.java">IconDemoApplet.java</a>, is a simple class that manages an image icon and its properties.<blockquote><pre>public class Photo { public String filename; public String caption; public int width; public int height; public ImageIcon icon; public Photo(String filename, String caption, int w, int h) { this.filename = filename; if (caption == null) this.caption = filename; else this.caption = caption; width = w; height = h; icon = null; } public void setIcon(ImageIcon i) { icon = i; } public ImageIcon getIcon() { return icon; }}</pre></blockquote><p>The <a href=#applet>Loading Images Into Applets</a> sectiondiscusses how images are loaded into this applet and showsthe <code>createAppletImageIcon</code> method — a versionof <code>createImageIcon</code> customized for applets that aredeployed using Java Plug-in.</blockquote><a name=getresource><h3>Loading Images Using getResource</h3></a><blockquote><p>Most often, an image icon's data comes from an image file.There are a number of valid ways that your application'sclass and image files may be configured on your file server.You might have your class files in a JAR file, oryour image files in a JAR file; they might bein the same JAR file, or they might be indifferent JAR files. The following figures illustrate a few ofthe ways these files can be configured:<h4 align=center><font color=red>[PENDING: New figures forthcoming. Thenew figures will show more family-tree style lines.]</font></h4><p><table cellpadding=5><tr align=center><td width=228><IMG SRC="../../figures/uiswing/components/default.gif" WIDTH="178" HEIGHT="93" ALT="Diagram showing MyDemo.class and images/myImage.gif under dot (parent directory)"></td><td width=282><IMG SRC="../../figures/uiswing/components/defaultImageJar.gif" WIDTH="232" HEIGHT="84" ALT="Diagram showing MyDemo.class and image.jar under dot (parent directory)"></td></tr><tr valign=top><td><font size=-2>Class file next to an image directory containing the image file,in GIF format. </font></td><td><font size=-2>Class file in same directory as JAR file. The JARfile was created with all the images in an<code>images</code> directory.</font></td></tr><tr align=center><td width=300><IMG SRC="../../figures/uiswing/components/defaultTwoJars.gif" WIDTH="250" HEIGHT="84" ALT="Diagram showing MyDemo.jar and image.jar under (parent directory)"></td><td><IMG SRC="../../figures/uiswing/components/megaJar.gif" WIDTH="" HEIGHT="" ALT="Diagram showing MyDemo.class and images/myImage.gif in the same JAR file."></tr><tr valign=top><td><font size=-2>Class file in one JAR file and the images in another JAR file.</font></td><td><font size=-2>Class and image files in same JAR file.</font></td></tr></table><p>If you are writing a real-world application, it is likely(and recommended) that you put your files into a package.For more information on packages, see<a class="TutorialLink" target="_top" href="../../java/package/packages.html">Creating and Using Packages</a> in the<a class="TutorialLink" target="_top" href="../../java/">Learning the Java Language</a> trail. Here are some possible configurations usinga package named "omega":<p><table cellpadding=5><tr align=center><td width=273><IMG SRC="../../figures/uiswing/components/omega.gif" WIDTH="223" HEIGHT="129" ALT="Diagram showing omega package with MyDemo.class and image/myImage.gif"></td><td width=372><IMG SRC="../../figures/uiswing/components/omegaImageJar.gif" WIDTH="322" HEIGHT="120" ALT="Diagram showing omega package with MyDemo.class and image.jar "></td></tr><tr valign=top><td><font size=-2>Class file in directory named <code>omega</code>.Image in <code>omega/images</code> directory.</font></td><td><font size=-2>Class file in <code>omega</code> directory.Image in JAR file not inside of <code>omega</code>directory, but created with <code>omega/images</code>hierarchy.</font></td></tr><tr align=center><td width=228><IMG SRC="../../figures/uiswing/components/megaOmegaJar.gif" WIDTH="178" HEIGHT="111" ALT="Diagram showing omega.jar which contains omega/MyDemo.class and omega/images/myImage.gif"></td></tr><tr valign=top><td><font size=-2>One big JAR file with class files under <code>omega</code> directoryand image files under <code>omega/images</code>directory.</font></td></tr></table><p>All seven configurations shown are valid, and the same code reads the image:<blockquote><pre>java.net.URL imageURL = myDemo.class.getResource("images/myImage.gif");...if (imageURL != null) { ImageIcon icon = newImageIcon(imageURL);}</pre></blockquote><p>The <code>getResource</code> method causes the class loader tolook through the directories and JAR files in the program's class path,returning a URL as soon as it finds the desired file.In our example the MyDemo program attempts to load the<code>image/myImage.gif</code> file. The class loader looksthrough the directories and JAR files inthe program's class path for <code>image/myImage.gif</code>.If the class loader finds the file, it returns the URLof the JAR file or directory that contained the file.If another JAR file or directory in the class path containsthe <code>images/myImage.gif</code> file, the class loader returns thefirst instance that contains the file.<blockquote><hr><strong>Version note:</strong> In versions of Java Plug-in before 1.4,<code>getResource</code> doesn't look in JAR files.See <a href=#applet>Loading Images Into Applets</a> for details.<hr></blockquote><p>Here are three ways to specify the class path:<ul><li>Using the <code>-cp</code> or <code>-classpath</code>command-line argument. For example, in the case where theimages are in a JAR file named <code>images.jar</code> andthe class file is in the current directory:<blockquote><pre>java -cp .;image.jar MyDemo [Microsoft Windows]java -cp ".;image.jar" MyDemo [Unix-emulating shell on Microsoft Windows — you must quote the specified path]java -cp .:image.jar MyDemo [Unix]</pre></blockquote><p>If your image and class files are inseparate JAR files, your command line will looksomething like:<blockquote><pre>java -cp .;MyDemo.jar;image.jar MyDemo [Microsoft Windows]</pre></blockquote><p>In the situation where all the files are in one JAR file,you can use either of the following commands:<blockquote><pre>java -jar MyAppPlusImages.jarjava -cp .;MyAppPlusImages.jar MyApp [Microsoft Windows]</pre></blockquote><p>For more information, see the<a class="TutorialLink" target="_top" href="../../deployment/jar/">JAR Files</a> trail.<p><li>In the program's JNLP file (used by Java Web Start). For example, here is the JNLP file used by <code>DragPictureDemo</code>:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -