GridBagLayout Java 中的边距/填充

2022-09-02 11:22:45
  1. 是否可以为整行/列设置边距/填充?我使用约束对象上的插图,但是,使用这种方法,我需要在每个组件上从底部设置填充。GridBagLayout

  2. 是否可以填充?因为现在每个组件都与框架对齐。JFrame

  constraints.weightx = 2;
  constraints.weighty = 1;
  constraints.fill = GridBagConstraints.BOTH;
  addComponent(this, layout, constraints, questionPanel = new QuestionPanel(), 0, 0, 1, 1);

  constraints.weightx = 1;
  constraints.weighty = 1;
  constraints.fill = GridBagConstraints.BOTH;
  addComponent(this, layout, constraints, categoryPanel = new CategoryPanel(), 0, 1, 1, 1);

  constraints.weightx = 1;
  constraints.weighty = 0;
  constraints.fill = GridBagConstraints.HORIZONTAL;
  addComponent(this, layout, constraints, answerPanel = new AnswerPanel(), 1, 0, 2, 1);

  constraints.weightx = 1;
  constraints.weighty = 2;
  constraints.fill = GridBagConstraints.BOTH;
  addComponent(this, layout, constraints, tabPane = new JTabbedPane(), 2, 0, 2, 1);

  constraints.weightx = 1;
  constraints.weighty = 0;
  constraints.fill = GridBagConstraints.NONE;
  constraints.anchor = GridBagConstraints.SOUTHEAST;
  addComponent(this, layout, constraints, buttonPanel = new ButtonPanel(), 3, 1, 1, 1);

我正在使用私有方法addComponent:

private void addComponent(Container context, GridBagLayout _layout, GridBagConstraints            _constraints, Component component, int row, int column, int width, int height) {
  _constraints.gridx = column;
  _constraints.gridy = row;
  _constraints.gridwidth = width;
  _constraints.gridheight = height;

  _layout.setConstraints(component, _constraints);
  context.add(component);
 }

如何在单元格之间添加一些“空气(填充/边距)”?


答案 1

使用类的属性insetGridBagConstraints

例如:

GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(3,3,3,3);

希望这就是你正在寻找的。


答案 2

据我所知,执行第一个任务的唯一方法是为每个约束设置一个 Insets 对象...(手动编码布局显然不是在Java中轻松设计的:P)

但是有一种非常简单的方法可以完成第二项操作,而不会弄乱任何插图或任何内容:将内容窗格的布局设置为具有所需的任何垂直和水平间隙的FlowLayout,向内容窗格添加面板,而不是将所有内容添加到内容窗格中,将其添加到新面板中。


推荐