Eric
Eric

Reputation: 2076

MigLayout JLabel exceeds constraints

I'm using MigLayout the following way

    panel.setLayout(new MigLayout("",
            "[][600!][]",
            "[][][][][][][][][]"));
    panel.add(composerTitle);
    panel.add(composerText, "wmax 600");
    panel.add(lblCount, "push, align right, wrap");
    panel.add(costTitle);
    panel.add(costText, "wrap,wmax 600");
    panel.add(titleTitle);
    panel.add(titleText, "wrap,wmax 600");
    panel.add(publisherTitle);
    panel.add(publisherText, "wrap,wmax 600");
    panel.add(scoreinfoTitle);
    panel.add(scoreinfoText, "wrap,wmax 600");
    panel.add(languageTitle);
    panel.add(languageText, "wrap,wmax 600");
    panel.add(collectionTitle);
    panel.add(collectionText, "wrap,wmax 600");
    panel.add(numbersTitle);
    panel.add(numbers, "grow, span 2, wrap");//JTextArea that uses line wrap
    panel.add(contentTitle);
    panel.add(content, "grow, span 2, wrap");//JTextArea

Sometimes my labels may exceed the 600! constraint I added for the column. Therefore, I expected for the labels to never exceed 600 because the max is set to 600. However, it is doing this if the label has enough text. Therefore I had to add the constraint to each one "wmax 600." Without that constraint, my label was running off the frame.

Is there a way to do this so I don't have to add "wmax 600" to each label that I add. It seems to defeat the purpose of the 600! constraint for the column.

Upvotes: 3

Views: 972

Answers (1)

kleopatra
kleopatra

Reputation: 51525

Base traits of MigLayout:

  • cell-size != component-size: row/column constraints only effect the former
  • it always respect a component's min/pref/max, except when overwritten in a ComponentConstraint

Those combined with a label having a minSize that's only slightly smaller than its prefSize lead to those overshooting (aka: > than cell width) component sizes. To at least decouple the component constraint from the column constraint (that is, not have to change all former when the latter changes) you can use the wmin:

JPanel panel = new JPanel();
panel.setLayout(new MigLayout("wrap 3, debug",
        "[][300!][]"));
panel.add(new JLabel("first, normal: "));
panel.add(new JLabel("and here we want something reaaly long" 
        + "and here we want something reaaly long")
          , "wmin 0"
        );
panel.add(new JLabel("10"));
panel.add(new JLabel("second: "));
panel.add(new JLabel("another"));

Alternatively (and if there are many such layouts in your application), subclass JLabel and override getMinPreferredSize to return (0, minHeight). Slightly dirty but a min arguably doesn't really make much sense for a JLabel: after all by default, it already can handle it a bit by showing the ellipsis and you might further enhance the subclass to show a tooltip with the complete text.

Upvotes: 6

Related Questions