How to Center a JLabel in Swing

Sheeraz Gul Feb 02, 2024
How to Center a JLabel in Swing

This tutorial demonstrates how to center a JLabel in Java Swing.

Center a JLabel in Swing

We can use the LayoutManager GridBagLayout to center the components in Swing. Similarly, we can center a JLabel using GridBagLayout.

Follow the steps below to center a JLabel in Java Swing.

  • First of all, create a JFrame.
  • Then, create a JPanel.
  • Now, create the JFrame, which will be centered.
  • Set layout in the JPanel as GridBagLayout.
  • Set the borders of JPanel.
  • Finally, get it done with the closing of JFrame.

Let’s try an example in Java based on the steps above.

package delftstack;

import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class Center_Jlabel {
  public static void main(String[] args) {
    JFrame J_Frame = new JFrame("Center Frame");
    JPanel J_Panel = new JPanel();
    JLabel J_Label = new JLabel("Centered Label for Name Field: ");
    JTextArea text = new JTextArea();
    text.setText("Add Name");
    J_Panel.setLayout(new GridBagLayout());
    J_Panel.add(J_Label);
    J_Panel.add(text);
    J_Panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    J_Frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    J_Frame.add(J_Panel);
    J_Frame.setSize(700, 300);
    J_Frame.setVisible(true);
  }
}

The code above will center a JLabel using Java Swing. See output:

Centered JLabel

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java Swing

Related Article - Java JLabel