next up previous
Next: Images as Labels Up: Labels and Icons Previous: Label Mnemonics

Label Alignment

You can control both the horizontalAlignment and verticalAlignment properties of a label's content (text and icon).

The methods setHorizontalAlignment() and setVerticalAlignment() are used with the following SwingConstants:

Note: We refer to an alignment by SwingConstants.CENTER for example.

You can also set the text position relative to an icon (if both defined) with setHorizontalTextPostion() and setVerticalTextPostion()

The following example AlignmentExample.java illustrates the above points and produces output like this:

Alignment of Labels

We simply set the labels' positions with:

label1.setVerticalAlignment(SwingConstants.BOTTOM);
    label2.setVerticalAlignment(SwingConstants.CENTER);
    label3.setVerticalAlignment(SwingConstants.TOP);

The full code listing for AlignmentExample.java is as follows:

// 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();
    frame.addWindowListener(new BasicWindowMonitor());
    Container c = frame.getContentPane();
    c.setLayout(new GridLayout(3,1));
    c.add(label1);
    c.add(label2);
    c.add(label3);
    frame.setSize(200,200);
    frame.setVisible(true);
  }
}



Dave Marshall
4/14/1999