Search code examples
javaswingsizecellgridbaglayout

GridBagLayout Maximum Cell size


It is possible to limit the cell size(height/width) in a GridBagLayout?

I mean.. i have a 2 rows that have same weightx = 0.5, but when i resize i don't want first row to get higher than 300 pixels.

Also i don't want it to not take any available space if it is smaller than 300. (setting weightx to 0). It makes no sense to set maximum size for my component in the cell, because when i resize all available space is filled with the component(component is resized to fill the cell).


Solution

  • To my knowledge it can't be done with GridBagLayout. Luckily there are alternatives. MiGLayout works similarly to GridBagLayout but is more powerful and more expressive. It is also cell-based and will let you set the minimum, preferred and maximum sizes of cells and rows/columns of cells

    Though I recommend you work out your own solution as this one relies too heavily on row constraints for my liking and is based on a few assumptions about what you want, here's an example:

    JPanel panel = new JPanel(new MigLayout("flowy, fillx, filly", "[fill, grow]", "[fill, 0:100:300][fill, 0:100:max(100%,300)]"));
    JPanel redPanel = new JPanel();
    redPanel.setBackground(Color.RED);
    JPanel bluePanel = new JPanel();
    bluePanel.setBackground(Color.BLUE);
    
    panel.add(redPanel);
    panel.add(bluePanel);
    
    JFrame frame = new JFrame();
    frame.add(panel);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);