I want to build this layout:
Which consists of a label, a text field, 2 buttons and a variable height text area (from 1 row to 40+ rows). I am trying to use a GridBagLayout
with no success. Buttons are on top of each other, I don't know how to set the size of each element and there is no space between them. Here is the code until now:
GridBagLayout gridbag = new GridBagLayout();
this.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
gridbag.setConstraints(lblGuidelines, c);
this.add(lblGuidelines);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 4;
gridbag.setConstraints(txtNumberInput, c);
this.add(txtNumberInput);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.weightx = 0.5;
gridbag.setConstraints(btnCheck, c);
this.add(btnCheck);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.weightx = 0.5;
gridbag.setConstraints(btnClear, c);
this.add(btnClear);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 4;
gridbag.setConstraints(textArea, c);
this.add(textArea);
Something like...
Basically, you need to set the gridx
position for the second button to be 1
and not 0
. Also, it's pointless to specify a gridwidth
where the columns don't exist, it can cause issues, but mostly, those columns will have a virtual width of 0
, so won't count for much
GridBagLayout gridbag = new GridBagLayout();
this.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JLabel lblGuidelines = new JLabel("Please neter a telephone number and check if it's valid or not");
JTextField txtNumberInput = new JTextField(12);
JButton btnCheck = new JButton("Check");
JButton btnClear = new JButton("Clear");
JTextArea textArea = new JTextArea(20, 12);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
c.insets = new Insets(8, 8, 8, 8);
c.weightx = 1;
this.add(lblGuidelines, c);
c.gridx = 0;
c.gridy = 1;
this.add(txtNumberInput, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.weightx = 0.5;
this.add(btnCheck, c);
c.gridx = 1;
c.gridy = 2;
this.add(btnClear, c);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
c.weightx = 1;
this.add(new JScrollPane(textArea), c);