Search code examples
javaswinglayout-managerjgoodiesform-layout

How to make large components not to blow up the layout when using JGoodies FormLayout?


I'm using JGoodies Forms 1.8.0

I've been having a problem when a single oversized label causes the entire layout to no longer fit in a window. I would like that text to be visually trimmed, so it's obvious for the user that the text doesn't fit, but the rest of the GUI should still keep fitting.

I prepared a simplified example that exhibits the same behaviour. Here everything works fine because the window is large enough:

And here the same window, but resized:

enter image description here

Notice that the rightmost columns are no longer visible.

The desired effect is as following:

  • if the text fits, it should be displayed in its entirety

  • if the text doesn't fit, then the end of it should be cut off

  • text should be left-aligned

  • all buttons should be visible, all the time

  • button 100 should be in the very corner of the window

Here is the code for the screenshots:

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

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

public class Test extends JFrame {

    Test() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(900, 600);

        JPanel left = new JPanel();
        left.setBackground(Color.BLUE);

        JPanel right = new JPanel();

        JLabel fox = new JLabel("The quick brown fox jumps over the lazy dog.");
        fox.setFont(new Font(null, 0, 50));

        JPanel rightBottom = new JPanel();
        rightBottom.setLayout(new GridLayout(10, 10));
        for (int i = 1; i <= 100; i++) {
            rightBottom.add(new JButton("butt" + i));
        }

        CellConstraints cc = new CellConstraints();
        this.setLayout(new FormLayout("100dlu,p:g", "f:p:g"));
        this.add(left, cc.xy(1, 1));
        this.add(right, cc.xy(2, 1));
        right.setLayout(new FormLayout("f:p:g", "p,5dlu,f:p:g"));
        right.add(fox, cc.xy(1, 1));
        right.add(rightBottom, cc.xy(1, 3));

    }

    public static void main(String[] args) {
        new Test().setVisible(true);
    }
}

Solution

  • The specification of preferred size makes the layout to display buttons at their preferred size. As a result some of the buttons do not fit. Try specifying a different constraint. For example, use a constant size with a combination of grow and fill. For example try these:

    this.setLayout(new FormLayout("100dlu,1dlu:g", "f:1dlu:g"));
    
    right.setLayout(new FormLayout("f:1dlu:g", "p,5dlu,f:1dlu:g"));
    

    At certain sizes button titles will not fit though.

    Here is a result:

    enter image description here