ant*_*abo 12 java layout user-interface swing
问题在于组件的居中布局,GridBagLayout总是"坐"在JPanel的中心,所以我不在乎它如何布局组件内部,我的问题是这些组件将开始在面板上布局.
我尝试过:
panel.setAlignmentX( JPanel.LEFT_ALIGNMENT );
Run Code Online (Sandbox Code Playgroud)
但它没有帮助.
任何的想法?
Nic*_*olt 19
您需要添加至少一个将填充水平空间的组件.如果您没有这样的组件,可以试试这个:
GridBagConstraints noFill = new GridBagConstraints();
noFill.anchor = GridBagConstraints.WEST;
noFill.fill = GridBagConstraints.NONE;
GridBagConstraints horizontalFill = new GridBagConstraints();
horizontalFill.anchor = GridBagConstraints.WEST;
horizontalFill.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JLabel("Left Aligned"), noFill);
panel.add(Box.createHorizontalGlue(), horizontalFill);
Run Code Online (Sandbox Code Playgroud)
除了设置anchor和fill字段外,您可能还需要设置weightx字段.这有助于指定调整大小的行为.
除非您为weightx或weighty指定至少一个非零值,否则所有组件在其容器的中心聚集在一起.这是因为当权重为0.0(默认值)时,GridBagLayout会在其单元格网格与容器边缘之间放置任何额外空间.
以下将保持myComponent固定在NORTHWEST角落.假设this是JPanel或类似:
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Specify horizontal fill, with top-left corner anchoring
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
// Select x- and y-direction weight. Without a non-zero weight,
// the component will still be centered in the given direction.
c.weightx = 1;
c.weighty = 1;
// Add child component
add(myComponent, c);
Run Code Online (Sandbox Code Playgroud)
要保持子组件左对齐但垂直居中,只需设置anchor = WEST和删除weighty = 1;.