A GridLayout
simply divides the available space into the specified number (in this case, 1 row and 3 columns) and makes each element occupy that entire space. In your case this gives two problems, because:
- The text box is very small, the same size as each button;
- The buttons take up the whole space, getting "stretched".
Also, I notice that you put the label and user box inside a panel, and used this panel on GridLayout
. Ideally the label would be on the main panel, and the box and two buttons inside it.
I will give a partial answer (because I have no way to test it now, and it’s been years since I work with Java, I’m not familiar with the new options of layout manager), that solves problems 2 and 3 but not 1. I will also try to risk a code to solve 1, using GridBagLayout
, but I can’t guarantee that it will work because my memory has been a bit flawed...
setLayout(new BorderLayout());
// O label vai no norte do cabeçalho
JLabel utilizador = new JLabel("Utilizador:");
add(utilizador, BorderLayout.NORTH);
// E o resto vai no centro
JPanel painel = new JPanel();
add(painel, BorderLayout.CENTER);
// O centro se divide em 3
painel.setLayout(new GridLayout(1,3));
// A caixa de texto e os 3 botões vão no centro
JTextField user = new JTextField();
JPanel auxOnline = new JPanel();
JPanel auxOffline = new JPanel();
painel.add(user);
painel.add(auxOnline);
painel.add(auxOffline);
// Mas os botões não vão diretamente pro centro; em vez disso, um
// painel auxiliar é criado para cada um deles de modo que não estiquem.
auxOnline.setLayout(new FlowLayout());
auxOnline.add(online);
auxOffline.setLayout(new FlowLayout());
auxOffline.add(offline);
To make the text box grow and occupy as much space as possible, but the buttons remain of your preferred size, an alternative is to use GridBagLayout
. Specifying where each element gets is a little more boring, but the end result is much greater flexibility in positioning:
setLayout(new BorderLayout());
// O label vai no norte do cabeçalho
JLabel utilizador = new JLabel("Utilizador:");
add(utilizador, BorderLayout.NORTH);
// E o resto vai no centro
JPanel painel = new JPanel();
add(painel, BorderLayout.CENTER);
// Em vez de Grid, usa GridBag
painel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5); // Margem externa de todos os componentes
// Coloca a caixa de texto; cresce horizontalmente
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
painel.add(user, c);
// Coloca os botões; não cresce
c.weightx = 0;
c.gridx++;
painel.add(online, c); // Não precisa de painel auxiliar
c.gridx++;
painel.add(offline, c);
After all, it will still be a 1x3 grid, but the first column will grow as the window size, while the other two will keep their preferred size.
Tutorial of GridBagLayout
(in English)
Thank you very much!!!
– rrr