Margin/padding in GridBagLayout Java

LuckyLuke picture LuckyLuke · Jan 30, 2011 · Viewed 32.7k times · Source
  1. Is it possible to set an margin/padding in GridBagLayout for the whole row/column? I use the inset on the constraints-object however, using this approach I need to set padding from bottom on every single component.

  2. Is it possible to pad all of the content in the JFrame? Because now every component is aligned with the frame.

  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);

I am using a private method 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);
 }

How can I add some "air(padding/margin)" between the cells?

Answer

InsolencE picture InsolencE · Jun 18, 2011

Use the inset property of the GridBagConstraints class

For example:

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

Hope this is what you are looking for.