问题
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
回答1:
Try with gc.weighty
...
gc.weightx = 2;
gc.weighty=1;
chatArea = new JTextArea();
...
JScrollPane scrollPane=new JScrollPane(chatArea);
chatCard.add(scrollPane,gc);
...
...
gc.weightx = 2;
gc.weighty=0;
JTextField msgField = new JTextField();
...
Add JTextArea
in JScrollPane
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:
回答2:
@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).
JPanel chatCard = new JPanel(new BorderLayout(5, 5));
int rows = 20;
int cols = 40;
JTextArea chatArea = new JTextArea(rows, cols);
chatCard.add(new JScrollPane(chatArea), BorderLayout.CENTER);
JTextField msgField = new JTextField(cols);
msgField.setActionCommand("SendText");
// msgField.addActionListener(listener);
chatCard.add(msgField, BorderLayout.PAGE_END);
来源:https://stackoverflow.com/questions/23047701/gridbaglayout-doesnt-fill-all-the-space