Java Reference
In-Depth Information
34.
{
35.
WebImageFrame wifr =
new
WebImageFrame();
36.
wifr.showIt("WebImageFrame: loading Image from the net");
37.
}
38.
}
■
15.4
Manipulating images
You may want to resize, rotate or reflect your image, or display only part of it,
rather than view it as it is stored on the hard disk. These operations are supported
by classes from the AWT library. We shall now introduce some techniques to solve
the aforementioned image manipulations. Class
Image
from the AWT library plays
a central role for image manipulations.
15.4.1
Loading images asynchronously
As mentioned above, loading a picture might take some time, especially if the
image has to be transferred over a network. To avoid blocking the main application
while the image is fetched, the loading process can be run asynchronously. Class
Toolkit
from the AWT library supplies methods for this purpose. We shall use
the
getImage
-method of the
default toolkit
to load images. One can specify the
name of the image file or a web location (URL) where the image is stored. Method
getImage
returns an object of class
Image
:
Image picture
=
Toolkit.getDefaultToolkit.getImage(String filename);
Image picture
=
Toolkit.getDefaultToolkit.getImage(String url);
Once the picture is loaded into an object of class
Image
,itcan be manipulated
by methods of this class. As a first application we show how a number of images
can be arranged. We derive class
ImagePanel
from
JPanel
.Animage panel will
automatically arrange pictures and display them. The background colour is set to
be yellow to emphasize the contrast to the pictures.
The images are displayed in method
paintComponent
of the panel. We use the
following method of class
Graphics
. The arguments are explained afterwards.
drawImage(Image picture,
int
left,
int
top, ImageObserver imObs)
The first argument (
picture
) contains the image to display. The two integer
arguments
left
and
top
specify the pixel position of the upper left corner of the
image inside the panel. The last argument is of type
ImageObserver
. This is an
interface from the AWT library which is of great help when loading or displaying
images. Fortunately, we do not have to implement this interface ourselves. Every
graphical component, regardless whether it is AWT or Swing, implements this
interface. We therefore can use
this
as image observer.
Search WWH ::
Custom Search