Рина Сергеева
Рина СергееваMay 9, 2018, 2:49 a.m.

How to make white spaces in the GridBagLayout manager

In my program, I decided to arrange GUI elements using the GridBagLayout manager. This is the most versatile layout manager. It places elements on a tabular basis, but each cell can have any size, width, height, etc.

You can see the method of placing elements of this manager on following image.

During the work with this layout manager, I had a question about how to make a white space between the elements. At the moment, I can offer several solutions of this problem.


Start with the fact that  by default the element placed on the panel has width and height of 1 cell.

The JTextFields from the picture above can be defined as follows:

JTextField textField = new JTextField();
constraints.gridwidth = 2;
  • constraints.gridwidth - responsible for the number of occupied cells horizontally;
  • constraints.gridheight - responsible for the number of occupied cells vertically;
  • constraints.gridx and constraints.gridy - responsible for the X-or Y-axis position of the object.

Make a  white space between elements in a line

To implement the white spaces, the first thing I came up with was the idea that you can just set the first element gridx = 0, and the other gridx = 2 (missing 1st). But this will work only if this line is not the first and before it were placed objects, the total or personal width of which was 3 or more. You can see on following image.

In other cases, you can make a white space between elements in a line with Box.createHorizontalStrut(50), which creates an invisible element of a specified size.

JButton button = new JButton("Start");
constraints.gridx = 0;
gblWidgetPanel.setConstraints(button, constraints);
widgetPanel.add(button);

constraints.gridx = 1;
widgetPanel.add(Box.createHorizontalStrut(50),constraints);

button = new JButton("Stop");
constraints.gridx = 2;
gblWidgetPanel.setConstraints(button, constraints);
widgetPanel.add(button);

Using Box.createVerticalStrut (int) similarly, you can create a white space between rows of elements.

The following method: the use of constraints.weighty and constaints.weightx .

If the resulting vertical or horizontal layout of all elements is smaller than the area they must fill, then all free space is distributed among the row or column elements according to their weight. The weight of a cell is specified in the constraints.weighty and constaints.weightx . It is set in a ratio of 100%. (for example: 0.5 = 50%). If you set zero, this element will not get additional space. By default, the values of all cells in the table are zero. There will be unused space between the top and bottom of the table.

For example:

JLabel label = new JLabel("Neo, what pill are you taking ?");
constraints.gridwidth = 1;      // how many cells does an object occupy
constraints.gridy = 0;          // what is the vertical cell number
constraints.weighty = 0.5;      // 50% free space
gblWidgetPanel.setConstraints(label, constraints);
widgetPanel.add(label);

JButton button = new JButton("Red");
constraints.gridy = 1;
constraints.weighty = 0.25;     // 25% free space
gblWidgetPanel.setConstraints(button, constraints);
widgetPanel.add(button);

button = new JButton("Blue");
constraints.gridy = 2;
constraints.weighty = 0.25;     // 25% free space
gblWidgetPanel.setConstraints(button, constraints);
widgetPanel.add(button);

And the last way for today: the use of EmptyBorder .

Allows the user to create an empty transparent border on GUI elements.

public EmptyBorder(int top,
                   int left,
                   int bottom,
                   int right)
label = new JLabel("Three);
constraints.gridy = 0;       // what is the vertical cell number
label.setBorder(BorderFactory.createEmptyBorder(10, 90, 0, 0));
gblWidgetPanel.setConstraints(label, constraints);
widgetPanel.add(label);

label = new JLabel("Two");
constraints.gridy = 1;       // what is the vertical cell number
label.setBorder(BorderFactory.createEmptyBorder(10, 60, 0, 0));
gblWidgetPanel.setConstraints(label, constraints);
widgetPanel.add(label);

label = new JLabel("One");
constraints.gridy = 2;       // what is the vertical cell number
constraints.gridx = 0;
label.setBorder(BorderFactory.createEmptyBorder(10, 30, 10, 0));
gblWidgetPanel.setConstraints(label, constraints);
widgetPanel.add(label);

label = new JLabel("Shall we go up the steps of the career ladder  ?");
label.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
constraints.gridy = 3;       // what is the vertical cell number
gblWidgetPanel.setConstraints(label, constraints);
widgetPanel.add(label);

Conclusion

there are 3 ways to make white spaces between elements using the GridBagLayout  manager:

- Box. createHorizontalStrut (int)   и  Box. createVerticalStrut(int)

- constraints.weighty и constaints.weightx

- EmptyBorder

Each of them is convenient in a certain situation. Which one to choose, you decide. Perhaps there are other ways not discussed in this article.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks