GridBagLayout doesn't fill all the space

2019-08-12 18:03发布

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

Panel with GridBagLayout

2条回答
地球回转人心会变
2楼-- · 2019-08-12 18:22

@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);
查看更多
何必那么认真
3楼-- · 2019-08-12 18:29

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:

enter image description here

查看更多
登录 后发表回答