Java program to center a JLabel in a JPanel with LayoutManager



In this article, we will create a graphical user interface (GUI) using the Swing. The Swing is the GUI framework for Java-based applications Here, we are using the LayoutManager GridBagLayout to center the components of AWT Layouts. We have two components here including a label and we have set the layout as GridBagLayout ?

JLabel label = new JLabel("Name (Centered Label): ");
JTextArea text = new JTextArea();
text.setText("Add name here...");
panel.setLayout(new GridBagLayout());

Steps to center a JLabel in a JPanel with LayoutManager

The following is an example to center a JLabel in a JPanel with LayoutManager ?

  • First, import the classes and packages.
  • Create JFrame and JPanel container.
  • Create JLabel and JTextArea components.
  • Set GridBagLayout to the JPanel.
  • Add components and set the border to the JPanel.
  • Add JPanel to the JFrame.
  • Set JFrame properties and make it visible.

Java program to center a JLabel in a JPanel with LayoutManager

The following is an example to center a JLabel in a JPanel with LayoutManager ?

package my;

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 SwingDemo {
  public static void main(String[] args) {
    JFrame frame = new JFrame("Demo Frame");
    JPanel panel = new JPanel();
    JLabel label = new JLabel("Name (Centered Label): ");
    JTextArea text = new JTextArea();
    text.setText("Add name here...");
    panel.setLayout(new GridBagLayout());
    panel.add(label);
    panel.add(text);
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.setSize(500, 300);
    frame.setVisible(true);
  }
}

Output

Code Explanation

It begins by importing necessary packages, including java.awt.GridBagLayout for layout management and javax.swing for GUI components. The SwingDemo class contains the main method, which creates a JFrame container titled "Demo Frame". Inside the frame, a JPanel container is created, and its layout is set to GridBagLayout to center components. A JLabel and JTextArea are created and added to the panel. The panel is given an empty border and then added to the frame. Finally, the frame is set to exit on close, sized to 500x300 pixels, and made visible. This results in a window with a centered label and text area, demonstrating basic Swing GUI creation.

Updated on: 2024-08-06T22:40:41+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements