Mega Code Archive

 
Categories / Java Tutorial / Swing
 

Positioning a component in the center of other component using GridbagLayout

import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Label; import javax.swing.JFrame; import javax.swing.JPanel; public class Main {   public static void main(String[] argv) {     JFrame demo = new JFrame("GridBag demo, to center a component");     JPanel parentPanel = new JPanel();     GridBagLayout gridbag = new GridBagLayout();     GridBagConstraints constraints = new GridBagConstraints();     constraints.fill = GridBagConstraints.CENTER;     gridbag.setConstraints(parentPanel, constraints);     parentPanel.setLayout(gridbag);     Label centerLabel = new Label(" AAA...");     parentPanel.add(centerLabel);     demo.add(parentPanel);     demo.setSize(500, 500);     demo.setVisible(true);   } }