Ofe*_*Ron 5 java user-interface swing layout-manager
我很想得到一个如何让这种粘合剂起作用的演示; 我一直试图让它发挥作用,没有任何反应......
一个很好的例子是实现的类CenteringPanel的:它是所有得到一个JComponent和中心它,离开它未拉伸上一个窗口的中心...我试图编码类似的东西:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的目标是使组件居中,那么GridBagLayout将很好地完成工作:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
GridBagLayout将创建一个填充面板的单个单元格.约束的默认值是水平和垂直对齐其单元格中的每个组件,并且既不填充方向.
如果你的目标是在BoxLayout中使用Glue来集中组件,那么这项工作就会复杂一些.使用垂直BoxLayout添加水平胶水没有帮助,因为组件是垂直堆叠的(对于水平BoxLayout也是如此).相反,您需要限制子项的大小并使用其对齐方式.我没有尝试过,但是对于垂直的BoxLayout,这样的东西应该可以工作:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8363 次 |
| 最近记录: |