If your goal is to center the component, then the GridBagLayout will do the job nicely:
public class CenteringPanel extends JPanel { public CenteringPanel(JComponent child) { GridBagLayout gbl = new GridBagLayout(); setLayout(gbl); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; gbl.setConstraints(child, c); add(child); } }
GridBagLayout will create a separate cell to fill the panel. The default value for constraints is to center each component in its cell both horizontally and vertically and not fill any direction.
If your goal is to use Clay in BoxLayout to center the component, then the job is a little more complicated. Adding horizontal glue with a vertical BoxLayout does not help, because the components are arranged vertically (and similarly for a horizontal BoxLayout). Instead, you need to limit the size of the child and use its alignment. I have not tried, but for a vertical BoxLayout something like this should work:
public class CenteringPanel { public CenteringPanel(JComponent child) { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); GridBagConstraints c = new GridBagConstraints(); child.setMaximumSize(child.getPreferredSize()); child.setAlignmentX(Component.CENTER_ALIGNMENT); add(Box.createVerticalGlue()); add(child); add(Box.createVerticalGlue()); } }
source share