Java Reference
In-Depth Information
The most important methods from
OFImage
for us are:
■
getPixel
and
setPixel
to read and modify single pixels
■
getHeight
and
getWidth
to find out about the image's size.
The
ImageFileManager
class offers three methods: one to read a named image file from
disk and return it as an
OFImage
, one to write an
OFImage
file to disk, and one to open a file-
chooser dialog to let a user select an image to open. The methods can read files in the standard
JPEG and PNG formats, and the
save
method will write files in JPEG format. This is done us-
ing the standard Java image I/O methods from the
ImageIO
class (package
javax.imageio
).
The
ImagePanel
class implements a custom-made Swing component to display our image.
Custom-made Swing components can easily be created by writing a subclass of an existing
component. As such, they can be inserted into a Swing container and displayed in our GUI like
any other Swing component.
ImagePanel
is a subclass of
JComponent
. The other important
point to note here is that
ImagePanel
has a
setImage
method that takes an
OFImage
as a pa-
rameter to display any given
OFImage
.
11.5.2
Adding the image
Now that we have prepared the classes for dealing with images, adding the image to the user
interface is easy. Code 11.4 shows the important differences from previous versions.
Code 11.4
ImageViewer
class
with
ImagePanel
public
class
ImageViewer
{
private
JFrame frame;
private
ImagePanel imagePanel;
//
Constructor and quit method omitted.
/**
* Open function: open a file chooser to select a new
* image file.
*/
private
void
openFile()
{
OFImage image = ImageFileManager.getImage();
imagePanel.setImage(image);
frame.pack();
}
/**
* Create the Swing frame and its content.
*/
Search WWH ::
Custom Search