![]() |
||
![]() |
![]() Alden Hosting provides professional, efficient, and reliable business-class Web hosting services to small- and medium-sized businesses. |
|
|
JAVA, JSP, SERVLETS, TOMCAT, SERVLETS MANAGER, |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
![]() |
| Class file next to an image directory containing the image file, in PNG format. |
Class file in same directory as JAR file. The JAR file was created
with all the images in an images directory.
|
![]() |
![]() |
| Class file in one JAR file and the images in another JAR file. | Class and image files in same JAR file. |
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 Creating and Using Packages in the Learning the Java Language trail. Here are some possible configurations using a package named "omega":
![]() |
![]() |
Class file in directory named omega. Image in
omega/images directory.
|
Class file in omega directory.
Image in JAR file not inside of omega directory, but
created with omega/images hierarchy.
|
![]() |
|
One big JAR file with class files under omega directory
and image files under omega/images directory.
|
All seven configurations shown are valid, and the same code reads the image:
java.net.URL imageURL = myDemo.class.getResource("images/myImage.gif");
...
if (imageURL != null) {
ImageIcon icon = new ImageIcon(imageURL);
}
The getResource method causes the class loader to
look through the directories and JAR files in the program's class
path, returning a URL as soon as it finds the desired file. In the
example the MyDemo program attempts to load the
images/myImage.png file from the omega
class. The class loader looks through the directories and JAR files
in the program's class path for /omega/images/myImage.png.
If the class loader finds the
file, it returns the URL of the JAR file or directory that
contained the file. If another JAR file or directory in the
class path contains the images/myImage.png file, the
class loader returns the first instance that contains the file.
Here are three ways to specify the class path:
Using the -cp or -classpath
command-line argument. For example, in the case where the images are in
a JAR file named images.jar and the class file is in the
current directory:
java -cp .;image.jar MyDemo [Microsoft Windows]
java -cp ".;image.jar" MyDemo [Unix-emulating shell on Microsoft
Windows — you must quote the path]
java -cp .:image.jar MyDemo [Unix]
If your image and class files are in separate JAR files, your command line will look something like:
java -cp .;MyDemo.jar;image.jar MyDemo [Microsoft Windows]
In the situation where all the files are in one JAR file, you can use either of the following commands:
java -jar MyAppPlusImages.jar java -cp .;MyAppPlusImages.jar MyApp [Microsoft Windows]
For more information, see the JAR Files trail.
In the program's JNLP file (used by Java Web Start). For example,
here is the JNLP file used by DragPictureDemo:
<?xml version="1.0" encoding="utf-8"?>
<!-- JNLP File for DragPictureDemo -->
<jnlp
spec="1.0+"
codebase="http://java.sun.com/docs/books/tutorialJWS/src/uiswing/misc/examples"
href="DragPictureDemo.jnlp">
<information>
<title>DragPictureDemo</title>
<vendor>The Java(tm) Tutorial: Sun Microsystems, Inc.</vendor>
<homepage href="http://java.sun.com/docs/books/tutorial/uiswing/misc/examples/index.html#DragPictureDemo"/>
<description>DragPictureDemo</description>
<description kind="short">A demo showing how to install
data transfer on a custom component.</description>
<offline-allowed/>
</information>
<resources>
<j2se version="1.6+"/>
<jar href="allClasses.jar"/>
<jar href="images.jar"/>
</resources>
<application-desc main-class="DragPictureDemo"/>
</jnlp>
In this example, the class files and the images files are in separate
JAR files. The JAR files are specified using the XML jar
tag.
Setting the CLASSPATH environment variable. This last
approach is not recommended. If CLASSPATH is not
set, the current directory (".") followed by the location of the system
classes shipped with the JRE are used by default.
Most of the Swing Tutorial examples put the images in an
images directory under the directory that contains the
examples' class files. When we create JAR files for the examples, we
keep the same relative locations, although often we put the class
files in a different JAR file than the image JAR file. No matter where
the class and image files are in the file system — in one JAR
file, or in multiple JAR files, in a named package, or in the default
package — the same code finds the image files using
getResource.
For more information, see Accessing Resources in a Location-Independent Manner and the Application Development Considerations.
Applets generally load image data from the computer that served up the applet. The
APPLETtag is where you specify information about the images used in the applet. For more information on theAPPLETtag see Using the APPLET Tag
Because the photograph images can be slow to access,
IconDemoApp.javauses aSwingWorkerto improve the performance of the program as perceived by the user.Background image loading — the program uses a javax.swing.SwingWorker object to load each photograph image and compute it's thumbnail in a background thread. Using a
SwingWorkerprevents the program from appearing to freeze up while loading and scaling the images.Here's the code to process each image:
SwingWorker invokes the/** * SwingWorker class that loads the images a background thread and calls publish * when a new one is ready to be displayed. * * We use Void as the first SwingWroker param as we do not need to return * anything from doInBackground(). */ private SwingWorkerloadimages = new SwingWorker () { /** * Creates full size and thumbnail versions of the target image files. */ @Override protected Void doInBackground() throws Exception { for (int i = 0; i < imageCaptions.length; i++) { ImageIcon icon; icon = createImageIcon(imagedir + imageFileNames[i], imageCaptions[i]); ThumbnailAction thumbAction; if(icon != null){ ImageIcon thumbnailIcon = new ImageIcon(getScaledImage(icon.getImage(), 32, 32)); thumbAction = new ThumbnailAction(icon, thumbnailIcon, imageCaptions[i]); } else { // the image failed to load for some reason // so load a placeholder instead thumbAction = new ThumbnailAction(placeholderIcon, placeholderIcon, imageCaptions[i]); } publish(thumbAction); } // unfortunately we must return something, and only null is valid to // return when the return type is void. return null; } /** * Process all loaded images. */ @Override protected void process(List chunks) { for (ThumbnailAction thumbAction : chunks) { JButton thumbButton = new JButton(thumbAction); // add the new button BEFORE the last glue // this centers the buttons in the toolbar buttonBar.add(thumbButton, buttonBar.getComponentCount() - 1); } } }; doInBackgroundmethod in a background thread. The method places a full size image, thumbnail size image and caption into aThumbnailActionobject. The SwingWorker then delivers theThumbnailActionto theprocessmethod. Theprocessmethod executes on the event dispatch thread and updates the GUI by adding a button to the toolbar.JButtonhas a constructor that takes an action object. The action object determines a number of the buttons properties. In our case the button icon, the caption and the action to be performed when the button is pressed is all determined by theThumbnailAction.Overhead — this program eventually loads all the source images into memory. This may not be desirable in all situations. Loading a number of very large files could cause the program to allocate a very large amount or memory. Care should be taken to manage the number and size of images that are loaded.
As with all performance-related issues, this technique is applicable in some situations and not others. Also the technique described here is designed to improve the program's perceived performance, but does not necessarily impact its real performance.
ThecreateImageIconmethod returns null when it cannot find an image, but what should the program do then? One possibility would be to ignore that image and move on. Another option would be to provide some sort of default icon to display when the real one cannot be loaded. Making another call tocreateImageIconmight result in another null so using that is not a good idea. Instead lets create a customIconimplementation.You can find the implementation of the custom icon class in
MissingIcon.java. Here are the interesting parts of its code:/** * The "missing icon" is a white box with a black border and a red x. * It's used to display something when there are issues loading an * icon from an external location. * * @author Collin Fagan */ public class MissingIcon implements Icon{ private int width = 32; private int height = 32; private BasicStroke stroke = new BasicStroke(4); public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.WHITE); g2d.fillRect(x +1 ,y + 1,width -2 ,height -2); g2d.setColor(Color.BLACK); g2d.drawRect(x +1 ,y + 1,width -2 ,height -2); g2d.setColor(Color.RED); g2d.setStroke(stroke); g2d.drawLine(x +10, y + 10, x + width -10, y + height -10); g2d.drawLine(x +10, y + height -10, x + width -10, y + 10); g2d.dispose(); } public int getIconWidth() { return width; } public int getIconHeight() { return height; } }The
paintIconmethod is passed aGraphicsobject. TheGraphicsobject gives thepaintIconmethod access to the entire Java2D API. For more information about painting and Java2D, see Performing Custom Painting.The following code demonstrates how the
MissingIconclass is used in theSwingWorkerdoInBackgroundmethod.private MissingIcon placeholderIcon = new MissingIcon(); ... if(icon != null) { ... } else { // the image failed to load for some reason // so load a placeholder instead thumbAction = new ThumbnailAction(placeholderIcon, placeholderIcon, imageCaptions[i]); }Using a custom icon has a few implications:
Because the icon's appearance is determined dynamically, the icon painting code can use any information — component and application state, for example — to determine what to paint.
- Depending on the platform and the type of image, you may get a performance boost with custom icons, since painting simple shapes can sometimes be faster than copying images.
Because
MissingIcondoes not do any file I/O there is no need for separate threads to load the image.
The following tables list the commonly used
ImageIconconstructors and methods. Note thatImageIconis not a descendent ofJComponentor even ofComponent.The API for using image icons falls into these categories:
- Setting, Getting, and Painting the Image Icon's Image
- Setting or Getting Information about the Image Icon
- Watching the Image Icon's Image Load
Setting, Getting, and Painting the Image Icon's Image Method or Constructor Purpose ImageIcon()
ImageIcon(byte[])
ImageIcon(byte[], String)
ImageIcon(Image)
ImageIcon(Image, String)
ImageIcon(String)
ImageIcon(String, String)
ImageIcon(URL)
ImageIcon(URL, String)Create an ImageIconinstance, initializing it to contain the specified image. The first argument indicates the source — image, byte array, filename, or URL — from which the image icon's image should be loaded. The source must be in a format supported by thejava.awt.Imageclass: namely GIF, JPEG, or PNG. The second argument, when present, provides a description for the image. The description may also be set viasetDescriptionand provides useful textual information for assistive technologies.void setImage(Image)
Image getImage()Set or get the image displayed by the image icon. void paintIcon(Component, Graphics, int, int) Paint the image icon's image in the specified graphics context. You would override this only if you're implementing a custom icon that performs its own painting. The Componentobject is used as an image observer. You can rely on the default behavior provided byComponentclass, and pass in any component. The twointarguments specify the top-left corner where the icon is painted.URL getResource(String)
in (java.lang.ClassLoader)Find the resource with the given name. For more information, see Loading Images Using getResource. InputStream getResourceAsStream(String)
in (java.lang.ClassLoader)Find the resource with the given name and return an input stream for reading the resource. For more information, see the Loading Images Into Applets discussion.
Setting or Getting Information about the Image Icon Method Purpose void setDescription(String)
String getDescription()Set or get a description of the image. This description is intended for use by assistive technologies. int getIconWidth()
int getIconHeight()Get the width or height of the image icon in pixels.
Watching the Image Icon's Image Load Method Purpose void setImageObserver(ImageObserver)
ImageObserver getImageObserver()Set or get an image observer for the image icon. int getImageLoadStatus() Get the loading status of the image icon's image. The values returned by this method are defined by MediaTracker.
The following table lists just a few of the many examples that use
ImageIcon.
Example Where Described Notes LabelDemoThis section and
How to Use LabelsDemonstrates using icons in an application's label, with and without accompanying text. IconDemoThis section Uses a label to show large images; uses buttons that have both images and text. CustomIconDemoThis section Uses a custom icon class implemented by ArrowIcon.java.TumbleItemHow to Make Applets An applet. Uses image icons in an animation. Shows how to call ImageIcon'spaintIconmethod.ButtonDemoHow to Use Buttons, Check Boxes, and Radio Buttons Shows how to use icons in an application's buttons. CheckBoxDemoHow to Use Check Boxes Uses multiple GIF images. TabbedPaneDemoHow to Use Tabbed Panes Demonstrates adding icons to tabs in a tabbed pane. DialogDemoHow to Make Dialogs Shows how to use standard icons in dialogs. TreeIconDemoHow to Use Trees Shows how to change the icons displayed by a tree's nodes. ActionDemoHow to Use Actions Shows how to specify the icon in a tool-bar button or menu item using an Action.FileChooserDemo2How to Use File Choosers Uses a PNGimage. Shows how to implement an image previewer and an image filter in a file chooser.
Note: The photographs used in theIconDemoare copyright ©2006 spriggs.net and licenced under a Creative Commons Licence.
Alden Hosting offers private JVM (Java Virtual Machine), Java Server Pages (JSP), Servlets, and Servlets Manager with our Web Hosting Plans WEB 4 PLAN and WEB 5 PLAN , WEB 6 PLAN .
At Alden Hosting we eat and breathe Java! We are the industry leader in providing affordable, quality and efficient Java web hosting in the shared hosting marketplace. All our sites run on our Java hosing platform configured for optimum performance using Java 1.6, Tomcat 6, MySQL 5, Apache 2.2 and web application frameworks such as Struts, Hibernate, Cocoon, Ant, etc.
We offer only one type of Java hosting - Private Tomcat. Hosting accounts on the Private Tomcat environment get their very own Tomcat server. You can start and re-start your entire Tomcat server yourself.
![]() |
|
http://alden-servlet-Hosting.com
JSP at alden-servlet-Hosting.com
Servlets at alden-servlet-Hosting.com
Servlet at alden-servlet-Hosting.com
Tomcat at alden-servlet-Hosting.com
MySQL at alden-servlet-Hosting.com
Java at alden-servlet-Hosting.com
sFTP at alden-servlet-Hosting.com
http://alden-tomcat-Hosting.com
JSP at alden-tomcat-Hosting.com
Servlets at alden-tomcat-Hosting.com
Servlet at alden-tomcat-Hosting.com
Tomcat at alden-tomcat-Hosting.com
MySQL at alden-tomcat-Hosting.com
Java at alden-tomcat-Hosting.com
sFTP at alden-tomcat-Hosting.com
http://alden-sftp-Hosting.com
JSP at alden-sftp-Hosting.com
Servlets at alden-sftp-Hosting.com
Servlet at alden-sftp-Hosting.com
Tomcat at alden-sftp-Hosting.com
MySQL at alden-sftp-Hosting.com
Java at alden-sftp-Hosting.com
sFTP at alden-sftp-Hosting.com
http://alden-jsp-Hosting.com
JSP at alden-jsp-Hosting.com
Servlets at alden-jsp-Hosting.com
Servlet at alden-jsp-Hosting.com
Tomcat at alden-jsp-Hosting.com
MySQL at alden-jsp-Hosting.com
Java at alden-jsp-Hosting.com
sFTP at alden-jsp-Hosting.com
http://alden-java-Hosting.com
JSp at alden-java-Hosting.com
Servlets at alden-java-Hosting.com
Servlet at alden-java-Hosting.com
Tomcat at alden-java-Hosting.com
MySQL at alden-java-Hosting.com
Java at alden-java-Hosting.com
sFTP at alden-java-Hosting.com
JSP
Servlets
Tomcat
mysql
Java
JSP
Servlets
Tomcat
mysql
Java
JSP
Servlets
Tomcat
mysql
Java
JSP
Servlets
Tomcat
mysql
Java
JSP at JSP.aldenWEBhosting.com
Servlets at servlets.aldenWEBhosting.com
Tomcat at Tomcat.aldenWEBhosting.com
mysql at mysql.aldenWEBhosting.com
Java at Java.aldenWEBhosting.com
Web Hosts Portal
Web Links
Web Links
Web Hosting
JSP Solutions Web Links
JSP Solutions Web Hosting
Servlets Solutions Web Links
Servlets Solutions Web Hosting
Web Links
Web Links
.
.
.
.
.
.
.
.
.
.
jsp hosting
servlets hosting
web hosting
web sites designed
cheap web hosting
web site hosting
myspace web hosting