Swing MigLayout - 当没有足够的空间时缩小标签

时间:2017-11-09 12:21:16

标签: java swing layout constraints miglayout

我试过让标签自动缩小,例如:

This is text变为This i...

但是,我无法做到这一点。

我的布局如下所示:

JPanel container = new JPanel(new MigLayout(new LC().fillX().gridGapX("2")));
container.add(new JXTitledSeparator("Text"), new CC().growX().spanX().wrap());

JLabel shrinkMeIfYouNeedTo = new JLabel("Shrink Shrink");
container.add( shrinkMeIfYouNeedTo, new CC());
container.add( infoText,  new JLabel("Great, long, beautiful info text that shall never shrink"), new CC().growX().spanX().wrap());

JScrollPane scrollPane = new JScrollPane(container);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

我已尝试使用shrinkXshrinkPrioX,但没有一个效果,minWidth("1")也没有效果。

1 个答案:

答案 0 :(得分:1)

由于我没有SwingX,而且我不知道infoText是什么,所以我无法提供所有内容。但是我给你的印象是这种行为:

Full Size

Starting To Shrink

Minimum Size

如果需要,可以通过将最小宽度和首选宽度设置为0,并将最大宽度设置为任意值来实现。有了String组件约束,您将像width 0:0:100那样做。


可运行示例

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;

import net.miginfocom.swing.MigLayout;

public class Test {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JPanel container = new JPanel(new MigLayout("fill, gapx 2", "grow"));
        container.add(new JLabel("Header", SwingConstants.CENTER), "split, span, growx, wrap");

        JLabel shrinkMeIfYouNeedTo = new JLabel("Shrink Shrink");
        container.add( shrinkMeIfYouNeedTo, "growx, width 0:0:100");
        container.add( new JLabel("Great, long, beautiful info text that shall never shrink"), "growx");

        JScrollPane scrollPane = new JScrollPane(container);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        frame.add(scrollPane);
        frame.setPreferredSize(new Dimension(800, 100));
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}