Java tutorial
//package com.java2s; //License from project: Open Source License import java.awt.Container; import javax.swing.JComponent; public class Main { public static void setBoundsAndCenterHorizontally(JComponent component, int x, int y, int width, int height) { Container parent = component.getParent(); int parentWidth = parent.getWidth(); int paddingOnBothSides = parentWidth - width; x = paddingOnBothSides / 2; component.setBounds(x, y, width, height); } }