GridBagLayout不会填满所有空间

时间:2014-04-13 19:56:41

标签: java swing layout-manager gridbaglayout

我有一个面板,用作卡片布局的一部分。该小组使用GridBagLayout。我添加了两个组件:JTextArea,填充设置为BOTH,JTextField,填充设置为水平。它们只占据了水平空间。

        // 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);

目前看起来像这样

Panel with GridBagLayout

2 个答案:

答案 0 :(得分:7)

尝试使用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();
    ...

JTextArea中添加JScrollPane,否则当行数大于其高度时,您会收到意外结果。

如果您想要从顶部/左侧/底部/右侧留出一些空间,请使用gc.insets=new Insets(5, 5, 5, 5);

快照:

enter image description here

答案 1 :(得分:3)

@Braj有GridBagLayout的答案 - 使用重量约束,并且他的答案是1+,但我认为如果使用BorderLayout,将你的JTextArea放在JScrollPane中,你的设置会好得多,放置JScrollPane BorderLayout.CENTER和JTextField BorderLayout.SOUTH(也称为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);