Search code examples
javaswingalignmentjlabellayout-manager

Make a JLabel text vertically aligned to the center


How do I make a JLabel text vertically and horizontally aligned to the center?

I have to make use of setHorizontalTextPosition and setVerticalTextPosition. Can this be achieved by using these 2?

I have tried but the text remains at the top itself.

 import java.awt.FlowLayout;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.SwingConstants;

public class label extends JFrame
{
  private JLabel label;

    public label() //constructor
    {
      super("Simple GUI");
      setLayout(new FlowLayout());

      label=new JLabel("Centered JLabel");
      label.setHorizontalTextPosition(SwingConstants.CENTER);
      label.setVerticalTextPosition(SwingConstants.CENTER);
      add(label);
    }
 }

Solution

  • I have tried but the text remains at the top itself.

    You have two problems:

    1. Andrew addressed the first problem. You are using the wrong method.
    2. Next you are using the wrong layout. The FlowLayout only display components on a single line so the component will always be at the top. Don't change the layout manager. The default layout manager for a JFrame is the BorderLayout. When you add a component to the CENTER (which is the default when you don't specify a constraint), the component will be sized to fill the entire frame. Then the "alignment" properties will control the position of the text within the size allocated to the label.

    Or a different option is to use a GridBagLayout. Then you don't need to play with alignment options of the component:

    setLayout( new GridBagLayout() );
    add(label, new GridBagConstraints());
    

    Try both options as both may be effective in different situations.

    Read the Swing tutorial on Layout Managers to better understand how each layout manager works.