Java Reference
In-Depth Information
int getImageHeight()
int getImageWidth()
ImageIcon() default constructor.
ImageIcon(Image picture) creates an ImageIcon out of an instance of the AWT
class Image .
ImageIcon(String filename) creates an ImageIcon from an image file, the
name of which is supplied in the argument filename .
ImageIcon(URL webaddress) creates an ImageIcon from a web address which is
supplied in the argument webaddress . Class URL is from the java.net library.
getImageHeight() returns the image height in pixels.
getImageWidth() returns the image width in pixels.
15.3
Displaying pixel graphics in Swing
Program ImageFrame demonstrates how a picture is loaded and displayed. We want
to display the image orange.png in a frame. The image is a digitized photo of size
400
400 pixels. Instances of class ImageIcon are non-graphical components.
They have to be displayed inside some graphical Swing component. We use a
JLabel for this purpose. In Section 3.3.1 we introduced the constructor
×
public JLabel(ImageIcon picture)
which we shall use now. We create an ImageIcon by passing the file name of the
!
image in the constructor. Note that you might have to adjust the path to match
your directory structure. To keep the program short, we do not check whether the
specified file really exists. The image is then displayed in the label. The size of the
label is adjusted so that it matches the image size, provided the layout manager of
the parent component allows that size. The label is centrally embedded into the
frame. We use the pack method of the parent frame to guarantee this. The result
is shown in Figure 15.1.
File: its/Images/ImageFrame.java
1.
package its.Images;
2.
3.
import its.SimpleFrame.SimpleFrame;
import javax.swing.*;
4.
5.
6.
7.
public class ImageFrame extends SimpleFrame
{
8.
9.
10.
private ImageIcon picture;
Search WWH ::




Custom Search