java - 使用 BoxLayout 垂直居中内容
问题描述
我正在尝试将 JPanel 的内容与 BoxLayout 垂直居中。BoxLayout 与 Y 轴对齐,因此内部的项目水平对齐。
例如,我现在拥有的:
-----------------------------
| ------ |
| ---------- |
| ---- |
| -------------- |
| |
| |
| |
| |
| |
| |
-----------------------------
我想要的是:
-----------------------------
| |
| |
| |
| ------ |
| ---------- |
| ---- |
| -------------- |
| |
| |
| |
-----------------------------
目前,我正在使用 setAlignmentX(Component.CENTER_ALIGNMENT) 将元素列居中:
JPanel box = new JPanel();
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
JLabel one = new JLabel("First element");
one.setAlignmentX(JLabel.CENTER_ALIGNMENT);
box.add(one);
JLabel two = new JLabel("Second element");
two.setAlignmentX(JLabel.CENTER_ALIGNMENT);
box.add(two);
...
我怎么能把它改成垂直居中?
解决方案
当BoxLayout
有额外空间可用时,布局允许组件增长(达到最大尺寸)。
您需要添加允许增长的组件。基本代码是:
box.add( Box.createVerticalGlue() );
box.add(...);
box.add( Box.createVerticalGlue() );
顶部/底部的两个“胶水”组件将增长以填充可用空间。
推荐阅读
- python - 如何可视化多元时间序列数据集
- c - C中是否有函数或语句来获取按键
- jquery - 使用 laravel 的多个插入动态输入字段
- python - 如果先前未定义变量,为什么匹配案例语句会分配给其中一种情况中使用的变量?
- webpack - Parcel with Pug,解析文件的路径名
- python - 如何将行转换为列?
- javascript - 当幻灯片在 Slick-slider 导航中处于活动状态时,如何删除不必要的背景?
- java - 无法正确计数字符
- postgresql - postgresql:不能在事务块内运行
- php - php 中的 recaptcha 仅没有 jquery 或 ajax