Java Reference
In-Depth Information
Code 11.1
A first version of an
ImageViewer class
frame = new JFrame( "ImageViewer" );
Container contentPane = frame.getContentPane();
JLabel label = new JLabel( "I am a label." );
frame.setVisible( true );
To get a GUI on screen, the first thing we have to do is create and display a frame. Code 11.1
shows a complete class (already named ImageViewer in preparation for things to come) that
shows a frame on screen. This class is available in the topic projects as imageviewer0-1 (the
number stands for version 0.1).
Exercise 11.1 Open the imageviewer0-1 project. (This will become the basis of your own
image viewer.) Create an instance of class ImageViewer . Resize the resulting frame (make it
larger). What do you observe about the placement of the text in the frame?
We shall now discuss the ImageViewer class shown in Code 11.1 in some detail.
The first three lines in that class are import statements of all classes in the packages java.awt ,
java.awt.event , and javax.swing . 1 We need many of the classes in these packages for all
Swing applications we create, so we shall always import the three packages completely in our
GUI programs.
Looking at the rest of the class shows very quickly that all the interesting stuff is in the make-
Frame method. This method takes care of constructing the GUI. The class's constructor contains
only a call to this method. We have done this so that all the GUI construction code is at a well-
defined place and is easy to find later (cohesion!). We shall do this in all our GUI examples.
The class has one instance variable of type JFrame . This is used to hold the frame that the im-
age viewer wants to show on screen. Let us now take a closer look at the makeFrame method.
The first line in this method is
frame = new JFrame("ImageViewer");
This statement creates a new frame and stores it in our instance variable for later use.
As a general principle, you should, in parallel with studying the examples in this topic, look at
the class documentation for all classes we encounter. This applies to all the classes we use; we
shall not point this out every time from now on, but just expect you to do it.
The swing package is really in a package called javax (ending with an x ), not java . The reason for
this is largely historic—there does not seem to be a logical explanation for it.
Search WWH ::

Custom Search