在GUI、java上使用胶水
我很想得到一个演示如何使这个胶水的东西工作;我一直在努力让它工作,但什么都没发生 一个很好的例子是类CenteringPanel的实现:它所做的只是获取一个JComponent并将其居中,使其未拉伸到窗口的中心。。。我试着编写这样的代码:在GUI、java上使用胶水,java,swing,user-interface,layout-manager,Java,Swing,User Interface,Layout Manager,我很想得到一个演示如何使这个胶水的东西工作;我一直在努力让它工作,但什么都没发生 一个很好的例子是类CenteringPanel的实现:它所做的只是获取一个JComponent并将其居中,使其未拉伸到窗口的中心。。。我试着编写这样的代码: import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JPanel; public class Cen
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());
}
}
如果您的目标是将一个组件居中,那么a将很好地完成这项工作:
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将创建填充面板的单个单元格。约束的默认值是使每个组件在其单元内水平和垂直居中,并且两个方向都不填充
如果您的目标是在BoxLayout中使用胶水使组件居中,那么这项工作就要复杂一些。使用垂直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());
}
}
为什么不使用BorderLayout并将组件放在中心位置呢?它会拉伸它,我不希望内容被拉伸。当
BoxLayout
垂直时,使用水平胶水有意义吗?我不知道,我是GUI新手,正在尝试学习。我一直在疯狂地阅读教程,但还没有理解胶水是如何工作的,我不确定,但我相信胶水可以将组件分开。因此,如果你在垂直胶水的上方和下方添加一个具有首选尺寸的组件,这可能会奏效。我仍然想了解胶水,但这也很好,你能解释一下你在那里做了什么吗?