I'd love to get a demonstration of how to make this glue thing work; I've been trying to get it to work and nothing happens...
A good example would be implementation of the class CenteringPanel: all it does is get a JComponent and centers it, leaving it unstretched on the center of a window... i tried coding something like that:
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class CenteringPanel extends JPanel{
private static final long serialVersionUID = 1L;
public CenteringPanel(JComponent toCenter) {
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
add(Box.createHorizontalGlue());
add(Box.createVerticalGlue());
add(toCenter);
add(Box.createVerticalGlue());
add(Box.createHorizontalGlue());
}
}
If your goal is to center a component, then a 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 single cell that fills the panel. The default value for the constraints are to center each component within its cell both horizontally and vertically and to fill in neither direction.
If your goal is to use Glue in a BoxLayout to center a component, then the job is a bit more complex. Adding horizontal glue with a vertical BoxLayout doesn't help, because the components are stacked vertically (and similarly for a horizontal BoxLayout). Instead you need to restrict the size of the child and use its alignment. I didn't try it, 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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With