Java GridBagLayout does not fill frame horizontally
Asked Answered
L

1

6

I am writing the GUI for a chat program. I can't seem to get the scroller to fill the frame horizontally and vertically and the messageInput to fill the frame horizontally. This is how it looks:

enter image description here

import javax.swing.*;
import java.awt.*;

public class GUI extends JFrame{

private JPanel panel;
private JEditorPane content;
private JTextField messageInput;
private JScrollPane scroller;
private JMenu options;
private JMenuBar mb;
private JMenuItem item;

public GUI(){
    /** This is the frame**/
    this.setPreferredSize(new Dimension(380,600));
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();
    panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    /** This is where the context shows up **/
    content = new JEditorPane();
    content.setEditable(false);

    /** Scroller that shows up in the context JEditorPane **/
    scroller = new JScrollPane(content);
    c.weightx = 0.0;
    c.weighty = 0.0;
    c.gridx = 0;
    c.gridy = 0;
    panel.add(scroller, c);

    /** This is where you type your message **/
    messageInput = new JTextField();
    c.weightx = 0.0;
    c.weighty = 0.0;
    c.gridx = 0;
    c.gridy = 1;
    c.weighty = 0.5;
    panel.add(messageInput, c);

    mb = new JMenuBar();
    options = new JMenu("Options");
    mb.add(options);
    this.setJMenuBar(mb);

    this.add(panel);
    this.pack();
    this.setVisible(true);

}



public static void main(String[] args) {
    new GUI();
}
}
Laboy answered 22/1, 2016 at 16:52 Comment(1)
It will never fill the cell as long as the weight is zero. The whole point of weight is to tell the GridBagLayout how much of the extra space should be given to that cell's contents.Lallygag
C
10

get the scroller to fill the frame horizontally and vertically and the messageInput to fill the frame horizontally.

You want to fill in both directions, so set

c.fill = GridBagConstraints.BOTH; // not HORIZONTAL

The next part is to fix the weights, which will tell how much space to allocate for each component (relatively):

    scroller = new JScrollPane(content);
    c.weightx = 0.5;
    c.weighty = 1.0;
    c.gridx = 0;
    c.gridy = 0;
    panel.add(scroller, c);

    messageInput = new JTextField();
    c.weightx = 0.5;
    c.weighty = 0.0;
    c.gridx = 0;
    c.gridy = 1;
    panel.add(messageInput, c);

weightx should be a non-zero value to allow the components to stretch horizontally. weighty should be non-zero for the editor, but not for the text field so that it won't take extra vertical space (in this case you don't need to set c.fill = GridBagConstraints.HORIZONTAL for it).

enter image description here

Cointon answered 22/1, 2016 at 22:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.