4.1 Labels


Swing allows you to create labels that can contain text, images, or both. We'll begin this chapter with a look at the JLabel class.

The JLabel class allows you to add basic, noninteractive labels to a user interface. Because of its inherent simplicity, there is no model class for JLabel. Figure 4-1 shows a class diagram for JLabel. We'll get into the two relationships to Icon a little later.

Figure 4-1. JLabel class diagram
figs/swng2.0401.gif

JLabel objects may consist of both text and graphics (icons), but for simple text-only labels, the interface with JLabel is very similar to that of java.awt.Label. The code to create and display a very simple text label looks like this:

// SimpleJLabelExample.java // import javax.swing.*; public class SimpleJLabelExample {   public static void main(String[] args) {     JLabel label = new JLabel("A Very Simple Text Label");     JFrame frame = new JFrame( );     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frame.getContentPane( ).add(label); // Adds to CENTER     frame.pack( );     frame.setVisible(true);   } }

Running this simple program produces the display shown in Figure 4-2.

Figure 4-2. A simple JLabel
figs/swng2.0402.gif

4.1.1 Properties

The JLabel class contains the properties shown in Table 4-1. The icon and disabledIcon properties specify the icon to be displayed by default and when the label is disabled, respectively. If an icon is specified without a disabledIcon, a disabledIcon is automatically created by converting the default icon to grayscale. The font property is shown in this table only because the setFont( ) method is overridden to call repaint( ) after calling super.setFont( ).

Table 4-1. JLabel properties

Property

Data type

get

is

set

Default value

UI

LabelUI

·

 

·

From L&F

UIClassIDo

String

     

"LabelUI"

accessibleContexto

AccessibleContext

·

   

JLabel.AccessibleJLabel

disabledIconb

Icon

·

 

·

null

displayedMnemonicb

int

·

 

·

KeyEvent.VK_UNDEFINED

displayedMnemonicIndex1.4, b

int

     

-1

fonto

Font

·

 

·

From L&F

horizontalAlignmentb

int

·

 

·

LEADING1.3

horizontalTextPositionb

int

·

 

·

TRAILING1.3

iconb

Icon

·

 

·

null

iconTextGapb

int

·

 

·

4

labelForb

Component

·

 

·

null

textb

String

·

 

·

null

verticalAlignmentb

int

·

 

·

CENTER

verticalTextPositionb

int

·

 

·

CENTER

1.3since 1.3, 1.4since 1.4, bbound, ooverridden

See also properties from the JComponent class (Table 3-6).

displayedMnemonic indicates the character to be used as an accelerator key, which typically means that an occurrence of this character is decorated with an underline in the label text. displayedMnemonicIndex is the index of the character that receives the decoration; it is set automatically to the first occurrence of the displayedMnemonic character in the label text. You can override this behavior by setting displayedMnemonicIndex to another index, or to -1 to force no decoration. (L&Fs are not technically required to honor the displayedMnemonicIndex property, but most of them do.)

The displayedMnemonic property is int because its value is intended to be one of the VK_ "virtual keycode" constants defined in java.awt.KeyEvent (see Table 27-6). However, a setDisplayedMnemonic( ) method, which takes a char is also defined. It's usually easier to call setDisplayedMnemonic('a') than it is to call setDisplayedMnemonic(KeyEvent.VK_A). If you use the char version, it doesn't matter if you specify an uppercase or lowercase character.

If the labelFor property has been set, the referenced component gains focus when the mnemonic is pressed in conjunction with the Alt key.[1] One common use of this feature is to apply mnemonics to labels appearing next to text fields, allowing the fields to gain focus when the shortcut key is pressed. We'll see an example of this strategy later in this section.

[1] This is actually up to the L&F, but the Basic L&F implements it this way, and none of the other Swing L&Fs change this behavior. On the Macintosh, the Option key is used for Alt; newer keyboards have both labels.

The horizontalAlignment and verticalAlignment properties are used to specify the alignment of the label's content (text and icon) within its interior. If a label is sized to be just large enough for its content (as FlowLayout does), setting these properties makes no difference. The values for these properties are defined in SwingConstants and must be LEADING, TRAILING, LEFT, RIGHT, or CENTER for horizontalAlignment, and TOP, BOTTOM, or CENTER for verticalAlignment. The LEADING and TRAILING constants were introduced in SDK 1.3 to accommodate locales in which text does not flow left-to-right. In the default locale, LEADING acts the same as LEFT, and TRAILING acts the same as RIGHT. In right-to-left locales, they are reversed. Prior to the introduction of these values, horizontalAlignment defaulted to LEFT, and horizontalTextPosition defaulted to RIGHT.

horizontalTextPosition , verticalTextPosition, and iconTextGap are meaningful only if both icon and text are defined. They designate the position of the label's text relative to its icon. Like the alignment properties, the valid values for the text position properties are LEFT, RIGHT, TOP, BOTTOM, and CENTER. (We'll cover these properties in more detail in the sections that follow.) The iconTextGap property reflects the space (in pixels) between the label's icon and text. Note that JLabel implements SwingConstants, so you can refer to the constant values listed in this paragraph as either SwingConstants.XYZ or JLabel.XYZ whichever you prefer.

The UI property holds a reference to the LabelUI object used to render the label.

4.1.1.1 displayedMnemonic and labelFor properties

The following example shows how the displayedMnemonic and labelFor properties can be used to direct focus to a component based on the mnemonic assigned to a label. All we do here is create three labels and three text fields, assigning one field to each label:

// MnemonicLabels.java // import javax.swing.*; import java.awt.*; // Shows how displayedMnemonic and labelFor properties work together public class MnemonicLabels {   public static void main(String[] args) {     JTextField firstField = new JTextField(10);     JTextField middleField = new JTextField(10);     JTextField lastField = new JTextField(10);     // Create labels and mnemonics.     JLabel firstLabel = new JLabel("First Name", JLabel.RIGHT);     firstLabel.setDisplayedMnemonic('F');     firstLabel.setLabelFor(firstField);     JLabel middleLabel = new JLabel("Middle Initial", JLabel.RIGHT);     middleLabel.setDisplayedMnemonic('I');     middleLabel.setDisplayedMnemonicIndex(7); // Requires 1.4     middleLabel.setLabelFor(middleField);     JLabel lastLabel = new JLabel("Last Name", JLabel.RIGHT);     lastLabel.setDisplayedMnemonic('L');     lastLabel.setLabelFor(lastField);     // Layout and display     JPanel p = new JPanel( );     p.setLayout(new GridLayout(3, 2, 5, 5));     p.add(firstLabel);     p.add(firstField);     p.add(middleLabel);     p.add(middleField);     p.add(lastLabel);     p.add(lastField);     JFrame f = new JFrame("MnemonicLabels");     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     f.setContentPane(p);     f.pack( );     f.setVisible(true);   } }

When executed, this example produces the display shown in Figure 4-3. The first letter in each label is underlined, based on the assigned mnemonic. Pressing Alt-F, Alt-I, or Alt-L causes focus to shift to the corresponding text field.

Figure 4-3. JLabels with mnemonics
figs/swng2.0403.gif

Note that calling middleLabel.setDisplayedMnemonicIndex(7) is incompatible with SDKs prior to 1.4, so remove that line of code if you want the program to run on older SDKs without throwing a NoSuchMethodError. Doing so will decorate the lowercase "i" in "Middle" instead of the uppercase "I" in "Initial," though.

4.1.2 Alignment

The following example shows the effects of JLabel horizontal and vertical alignment:

// AlignmentExample. java // import javax.swing.*; import java.awt.*; public class AlignmentExample {   public static void main(String[] args) {     // Create the labels and set alignment.     JLabel label1 = new JLabel("BottomRight", SwingConstants.RIGHT);     JLabel label2 = new JLabel("CenterLeft", SwingConstants.LEFT);     JLabel label3 = new JLabel("TopCenter", SwingConstants.CENTER);     label1.setVerticalAlignment(SwingConstants.BOTTOM);     label2.setVerticalAlignment(SwingConstants.CENTER);     label3.setVerticalAlignment(SwingConstants.TOP);     // Add borders to the labels (more on Borders later in the book).     label1.setBorder(BorderFactory.createLineBorder(Color.black));     label2.setBorder(BorderFactory.createLineBorder(Color.black));     label3.setBorder(BorderFactory.createLineBorder(Color.black));     // Put it all together.     JFrame frame = new JFrame("AlignmentExample");     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     JPanel p = new JPanel(new GridLayout(3, 1, 8, 8));     p.add(label1);     p.add(label2);     p.add(label3);     p.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));     frame.setContentPane(p);     frame.setSize(200,200);     frame.setVisible(true);   } }

Figure 4-4 shows the result of running this program.

Figure 4-4. JLabel alignment
figs/swng2.0404.gif

If you're familiar with pre-Swing java.awt.Labels, you'll appreciate the ability to specify a vertical alignment; the java.awt.Label class sets only horizontal alignment. (A java.awt.Label's horizontal alignment can be set via an argument to its constructors. Because the JLabel constructors are modeled after those of java.awt.Label, the JLabel class provides the same type of flexibility and has constructors that support specifying the horizontal position of the label. In contrast, the vertical position of a JLabel can be set only through the setVerticalAlignment( ) method.)



Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net