0

The default JLabel draws its text at the middle of its bounds. For example, if height of the label is 20, font height is 14, the Y coordinate would be (20 - 14)/2 = 3. Like this:

Red line is the JLabel bounds

What should I do if want to align the text to the TOP of the JLabel bounds? Like this:

Red line is the JLabel bounds

UPD:

public class LabelTest extends JFrame {

    public LabelTest() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 500);

        setLocationRelativeTo(null);

        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS));

        contentPanel.add(Box.createHorizontalStrut(10));

        final JLabel label1 = new JLabel("JLabel");
        label1.setVerticalAlignment(SwingConstants.TOP); // by the answer of Kevin Workman, doesn't help
        label1.setBorder(BorderFactory.createLineBorder(Color.RED));
        label1.setFont(new Font("Arial", Font.PLAIN, 14));
        contentPanel.add(label1);

        setContentPane(contentPanel);

        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LabelTest();
            }
        });
    }
}
SeniorJD
  • 6,946
  • 4
  • 36
  • 53

2 Answers2

2

You should be packing the frame. If you so this, there should be no unused space in the label. If you want empty space, use an empty border

label.setBorder(new EmptyBorder(0, 0, 5, 0));

                           top, left, bottom, right

Also, don't set sizes, Use Layout Mangers and let them do the sizing for you. Setting sizes will give you. Setting sizes will give you a rigid look that may look and perform differently on different platforms. Layout Managers will allow your GUI to be more fluid and adaptable to different environments.

See Laying out Components Within a Container for more information on working with layouts

Also see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?


Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
1

As always, the API is your best friend: http://docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html#setVerticalAlignment(int)

Edit- Based on your updated SSCCE, the problem is that your BoxLayout is shrinking the JLabel as small as it will go, so the vertical text position doesn't really matter. Try using a BorderLayout to check that.

The problem is that the insets of the JLabel are adding a small space to the top and bottom of the JLabel, so your text looks centered even though it's at the top. Here's a fix for the insets problem: How to change gap in swing label

Community
  • 1
  • 1
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107