How to center a JLabel in a JPanel with GridBagLayout in Java?


Center a component in a JPanel with GridBagLayout. Let us first create a JFrame and JPanel inside it -

JFrame frame = new JFrame("Demo Frame");
JPanel panel = new JPanel();

Now, we will add our components −

JLabel label = new JLabel("Demo Label (Centered)");
label.setForeground(Color.white);
JCheckBox checkBox = new JCheckBox("Checkbox (Centered)");

Set the layout −

panel.setLayout(new GridBagLayout());

The following is an example to center a label in a panel with GridBagLayout −

Example

package my;
import java.awt.Color;
import java.awt.GridBagLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
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("Demo Label (Centered)");
      label.setForeground(Color.white);
      JCheckBox checkBox = new JCheckBox("Checkbox (Centered)");
      panel.setLayout(new GridBagLayout());
      panel.add(label);
      panel.add(checkBox);
      panel.setBackground(Color.blue);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.setSize(600, 400);
      frame.setVisible(true);
   }
}

Output


Updated on: 30-Jul-2019

603 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements