Search code examples
javaswingresizegridbaglayoutpreferredsize

size of components in GridBagLayout is not correct


I'm making a simple interface in Java. I want to have on top a JButton with a set size of 200*20 and directly under it a JScrollPane encapsulating a JTextArea. The size of this field should be the remaining width and height of the JPanel in which it is placed (but with a minimum of 640*480) and must resize when making the window larger/smaller (until its minimum size).

I tried making this with a GridBagLayout but this does not seem to be working. Does somebody know how I can fix this?

    //Initialize components
    Dimension minSize = new Dimension(640, 480);
    info = new JTextArea("hello");
    info.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(info);
    scrollPane.setMinimumSize(minSize);
    JButton update = new JButton("update");
    JPanel jp = new JPanel();
    jp.setLayout(new GridBagLayout());
    GridBagConstraints grid = new GridBagConstraints();

    //add components
    grid.fill = GridBagConstraints.NONE;
    grid.anchor = GridBagConstraints.NORTHWEST;
    grid.gridheight = 1;
    grid.gridwidth = 1;
    grid.weighty = 1.0;
    grid.weightx = 1.0;
    grid.gridx = 0;
    grid.gridy = 0;

    jp.add(update, grid);

    grid.fill = GridBagConstraints.BOTH;
    grid.gridx = 0;
    grid.gridy = 1;
    grid.weighty = 15;
    grid.gridheight = 15;
    grid.gridwidth = 15;

    jp.add(scrollPane, grid);

    this.add(jp,BorderLayout.NORTH);

This is how it looks now: enter image description hereas I described before this is not what I want; the TextArea needs to fill the entire screen (so it needs to be taller).

How can I do this?


Solution

  • this.add( jp, BorderLayout.CENTER );

    As specified in the documentation:

    The components are laid out according to their preferred sizes and the constraints of the container's size. The NORTH and SOUTH components may be stretched horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may stretch both horizontally and vertically to fill any space left over.