I have a panel which is used as a part of card layout. The panel uses GridBagLayout
. I add two components to it: JTextArea
with fill set to BOTH and JTextField
with fill set to horizontal. They are only taking up the horizontal space.
// Chat card setup
JPanel chatCard = new JPanel(new GridBagLayout());
gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.fill = GridBagConstraints.BOTH;
gc.weightx = 2;
chatArea = new JTextArea();
chatCard.add(chatArea,gc);
gc.gridx = 0;
gc.gridy = 1;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.anchor = GridBagConstraints.PAGE_END;
gc.weightx = 2;
JTextField msgField = new JTextField();
msgField.setActionCommand("SendText");
msgField.addActionListener(listener);
chatCard.add(msgField, gc);
It currently looks like this
@Braj has the answer for GridBagLayout -- use the weighty constraint, and 1+ to his answer, but I think that your set up would be much better if you used a BorderLayout, placed your JTextArea in a JScrollPane, placed the JScrollPane BorderLayout.CENTER and the JTextField BorderLayout.SOUTH (also known as BorderLayout.PAGE_END).
Try with
gc.weighty
Add
JTextArea
inJScrollPane
otherwise you will get an unexpected result when the rows are larger than its height.use
gc.insets=new Insets(5, 5, 5, 5);
if you want some space from top/left/bottom/right.Snapshot: