Using Glue on GUI, java

I would like to get a demonstration of how to make this glue work; I tried to make it work, and nothing happens ...

A good example would be the implementation of the CenteringPanel class: all it does is get the JComponent and center it, leaving it unstretched in the center of the window ... I tried to code something like this:

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()); } } 
+4
source share
1 answer

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()); } } 
+4
source

Source: https://habr.com/ru/post/1388769/


All Articles