So I have the following Java Code which produces what you see in the image. The layout is pretty much what I wanted except that the buttons are stretched to be equal size and fill. Is there anyway to avoid this without using GridBagLayout like other answers suggest? I tried setting the size of the panel inside to something smaller but it got stretched anyway.
Code:
//Set-up main window
JFrame mainwindow = new JFrame();
mainwindow.setSize(500, 500);
mainwindow.setTitle("Example");
//Add components
JTabbedPane tabs = new JTabbedPane();
GridLayout experimentLayout = new GridLayout(0,2,0,5);
JPanel pnl_Logon = new JPanel();
pnl_Logon.setLayout(experimentLayout);
JLabel lbl_Username = new JLabel("Username: ");
JLabel lbl_Password = new JLabel("Password: ");
JTextField txt_Username = new JTextField(10);
JPasswordField psw_Password = new JPasswordField(10);
JButton btn_Logon = new JButton("Logon");
JButton btn_Clear = new JButton("Clear");
pnl_Logon.add(lbl_Username);
pnl_Logon.add(txt_Username);
pnl_Logon.add(lbl_Password);
pnl_Logon.add(psw_Password);
pnl_Logon.add(btn_Logon);
pnl_Logon.add(btn_Clear);
tabs.addTab("Logon", pnl_Logon);
//Draw window
mainwindow.add(tabs);
mainwindow.show();
Result:
The
GridLayout
manager does not honour the minimum, preferred, and maximum size values of its children. All the cells inGridLayout
have the same size. The size of each cell is equal to the size of a cell with the largest component. It is not a very useful manager and it seldom can be used in real-world applications. But what it seems to do is to create confusion.You mentioned that you would like to avoid the
GridBagLayout
manager. But there are many other options. This kind of layout can be easily accomplised with more flexible managers.I provide a simple solution with a
MigLayout
manager.MigLayout
is a grid-based layout manager too and this kind of layout can be easily created in a few lines.I do not know how exactly you wanted this layout so I created it my way. The text fields grow horizontally and the two buttons are horizontally aligned to the center.
For the reasons mentioned here, don't use
setSize()
this way. Instead, let each component adopt it's preferred size andpack()
the enclosingWindow
. In this case, add each button to a panel having the defaultFlowLayout
, which respects preferred size, as shown here.