Java Reference
In-Depth Information
12.5 Displaying Text and Images in a Window
Our next example introduces a framework for building GUI applications. Several concepts
in this framework will appear in many of our GUI applications. This is our first example
in which the application appears in its own window. Most windows you'll create that can
contain Swing GUI components are instances of class JFrame or a subclass of JFrame .
JFrame is an indirect subclass of class java.awt.Window that provides the basic attributes
and behaviors of a window—a title bar at the top, and buttons to minimize , maximize and
close the window. Since an application's GUI is typically specific to the application, most
of our examples will consist of two classes—a subclass of JFrame that helps us demonstrate
new GUI concepts and an application class in which main creates and displays the appli-
cation's primary window.
Labeling GUI Components
A typical GUI consists of many components. GUI designers often provide text stating the
purpose of each. Such text is known as a label and is created with a JLabel —a subclass of
JComponent . A JLabel displays read-only text, an image, or both text and an image. Ap-
plications rarely change a label's contents after creating it.
Look-and-Feel Observation 12.6
Text in a JLabel normally uses sentence-style capitalization.
The application of Figs. 12.6-12.7 demonstrates several JLabel features and presents
the framework we use in most of our GUI examples. We did not highlight the code in this
example, since most of it is new. [ Note: There are many more features for each GUI com-
ponent than we can cover in our examples. To learn the complete details of each GUI
component, visit its page in the online documentation. For class JLabel , visit
docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html .]
1
// Fig. 12.6: LabelFrame.java
2
// JLabels with text and icons.
3
import java.awt.FlowLayout; // specifies how components are arranged
4
import javax.swing.JFrame; // provides basic window features
5
import javax.swing.JLabel; // displays text and images
6
import javax.swing.SwingConstants; // common constants used with Swing
7
import javax.swing.Icon; // interface used to manipulate images
8
import javax.swing.ImageIcon; // loads images
9
10
public class LabelFrame extends JFrame
11
{
12
private final JLabel label1; // JLabel with just text
13
private final JLabel label2; // JLabel constructed with text and icon
14
private final JLabel label3; // JLabel with added text and icon
15
16
// LabelFrame constructor adds JLabels to JFrame
17
public LabelFrame()
18
{
Fig. 12.6 | JLabels with text and icons. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search