Java Reference
In-Depth Information
We then create a label component (type JLabel ) and add it to the content pane. A label is a
component that can display text and/or an image.
Finally, we have the two lines
frame.pack();
frame.setVisible(true);
The first line causes the frame to arrange the components inside it properly and to size itself
appropriately. We always have to call the pack method on the frame after we have added or
resized components.
The last line finally makes the frame visible on screen. We always start out with the frame
being invisible so that we can arrange all the components inside the frame without the con-
struction process being visible on screen. Then, when the frame is built, we can show it in a
completed state.
Exercise 11.3 Another often-used Swing component is a button (type JButton ). Replace
the label in the example above with a button.
Exercise 11.4 What happens when you add two labels (or two buttons) to the content
pane? Can you explain what you observe? Experiment with resizing the frame.
11.4.3
An alternative structure
We have chosen to develop our application by creating a JFrame object as an attribute
of the ImageViewer and populating it with further GUI components that are created
outside the frame object. An alternative structure for this top level would be to define
ImageViewer as a subclass of JFrame and populate internally. This style is also com-
monly seen. Code 11.2 shows the equivalent of Code 11.1 in this style. This version is
available as the project imageviewer0-1a . While it is worth being familiar with both styles,
neither is obviously superior to the other, and we will continue with our original version in
the rest of this chapter.
Code 11.2
An alternative structure
for the ImageViewer
class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// Comment omitted.
public class ImageViewer extends JFrame
{
/**
* Create an ImageViewer and show it on screen.
*/
public ImageViewer()
 
Search WWH ::




Custom Search