java - GridBagLayout 忽略锚点
问题描述
我的 GridBagLayout 有一些问题我想把按钮放在屏幕的左侧,就像现在一样。我知道我的体重为 0,但将其更改为 1 会破坏星座,我不知道如何将两者存档。
public class CreatePanel extends JPanel {
private static final Insets WEST_INSETS = new Insets(5, 0, 5, 1);;
public CreatePanel(JPanel mainPanel) {
setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
this.mainPanel = mainPanel;
setPreferredSize(new Dimension(400, 200));
setBackground(Color.GRAY);
add(Box.createVerticalGlue());
add(createGameLabel());
add(Box.createRigidArea(new Dimension(0,100)));
add(createJPanel());
add(Box.createVerticalGlue());
add(Box.createVerticalGlue());
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.insets = WEST_INSETS;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
return gbc;
}
private JPanel createJPanel() {
bottemPanel = new JPanel();
bottemPanel.setBackground(Color.ORANGE);
bottemPanel.setLayout(new GridBagLayout());
gbc = createGbc(0,0);
gbc.gridwidth=2;
bottemPanel.add(createRandomWordButton(),gbc);
gbc = createGbc(0,1);
bottemPanel.add(createWordTextField(),gbc);
gbc = createGbc(1,1);
bottemPanel.add(createUseWordButton(),gbc);
return bottemPanel;
}
private JLabel createGameLabel() {...}
private JButton createUseWordButton() {...}
private JTextField createWordTextField() {...}
}
解决方案
我知道我的体重为 0,但将其更改为 1 休息...
看起来您正在使用 BoxLayout 将子面板垂直居中。但是,默认情况下,JPanel 在可用空间中水平居中。因此,在您的 createJPanel 方法中尝试添加:
bottom.setAlignmentX(0.0f);
如果这不起作用,您可能需要为底部面板使用包装面板:
//return bottemPanel;
JPanel wrapper = new JPanel(); //
wrapper.setAlignmentX(0.0f);
wrapper.add(bottom);
return bottomPanel;
或者另一种解决方案是添加一个weightx
值为 1.0f 的虚拟组件。
JLabel dummy = new JLabel(" ");
gbc.gridx = ?;
gbc.weightx = 1.0f;
add(dummy, gbc);
推荐阅读
- unity3d - 如何为unity3D制作可编辑的网格
- r - 如何将分类文件链接到框架中的标识符?
- r - 将日期对象强制转换为 POSIXct 对象
- c# - 仅当具有唯一 11 个字符代码的所有文件都存在时才处理文件
- flutter - onTap 转到下一个列表项 (Flutter)
- python - Python 3.7:导入 websockets 模块时出现 NameError
- matlab - 试验台和平衡算法
- sequelize.js - sequelize.js 迁移执行顺序
- hibernate - Jpa Hibernate:读取更新值问题
- python - 在 Python 中使用正则表达式从字符串中提取数字(包括破折号)