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

Java 8Object Oriented ProgrammingProgramming

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


raja
Published on 31-May-2019 11:54:56
Advertisements