Java 使用MigLayout don';t调整后容器的大小

Java 使用MigLayout don';t调整后容器的大小,java,swing,layout-manager,miglayout,Java,Swing,Layout Manager,Miglayout,我试着写一个有3个垂直部分的面板:顶部生长、中间固定和底部生长 顶部是一个带有标记的JLabel。中间也是一个Jlabel,底部当前是一个空的JPanel 放大窗口可以: 当我重新调整窗口大小时,内容不会重新调整大小(请注意,问题不是字体大小,而是容器宽度): 仅当在计时器JLabel上调用重写的方法paint(见下文)中的setFont时,此问题才存在 public class TabRace extends JPanel { private JLabel timer;

我试着写一个有3个垂直部分的面板:顶部生长、中间固定和底部生长

顶部是一个带有标记的JLabel。中间也是一个Jlabel,底部当前是一个空的JPanel

放大窗口可以:

当我重新调整窗口大小时,内容不会重新调整大小(请注意,问题不是字体大小,而是容器宽度):

仅当在计时器JLabel上调用重写的方法paint(见下文)中的setFont时,此问题才存在

public class TabRace extends JPanel {
    private JLabel timer;

    public TabRace() {
        super();

        // Set the layout
        this.setLayout(new MigLayout("","[grow]","[grow][][grow]"));

        // Timer label
        timer = new JLabel("00:00:00.000");
        timer.setOpaque(true);
        timer.setBackground(new Color(0, 0, 0));
        timer.setForeground(new Color(255, 255, 255));
        this.add(timer,"grow,wrap");

        // Table label
        JLabel tableCaption = new JLabel("Last Records:");
        this.add(tableCaption,"wrap");

        JPanel bottom = new JPanel();
        this.add(bottom, "grow,wrap");

    }

    public void paint(Graphics g) {
        super.paint(g);

        // Thanks to coobird
        // @see https://stackoverflow.com/questions/2715118/how-to-change-the-size-of-the-font-of-a-jlabel-to-take-the-maximum-size

        Font labelFont = timer.getFont();
        final int stringWidth = timer.getFontMetrics(labelFont).stringWidth(timer.getText());
        final int componentWidth = timer.getWidth();

        // Find out how much the font can grow in width.
        double widthRatio = (double)componentWidth / (double)stringWidth;

        int newFontSize = (int)(labelFont.getSize() * widthRatio);
        int componentHeight = timer.getHeight();

        // Pick a new font size so it will not be larger than the height of label.
       int fontSizeToUse = Math.min(newFontSize, componentHeight);

       // Set the label's font size to the newly determined size.

       // REMOVING NEXT LINE AND RESIZING IS WORKING
       timer.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));

    }

}

我也试着把JLabel放在JPanel里面。有什么想法吗?

我不知道为什么,但在第一个JLabel(或其他行)中添加最小宽度可以解决这个问题:

this.add(timer,"grow,wrap,wmin 10");

为什么要在“绘制覆盖”中执行此操作?这对我来说似乎很危险。为什么不改为使用ComponentListener呢。我可以尝试使用Listener,您不应该在paint中修改组件的状态。这完全没有道理,为什么要这么做?更改字体大小如何影响组件的最终状态?调用paint时,组件的大小已经计算好了,所以你实际上在撒谎…@MadProgrammer上面的消息是写给我的吗?还是我只是误解了你的意思?干杯:-)这是因为最小尺寸和首选尺寸之间的差异是组件的收缩趋势。对于标签,
MigLayout
似乎将这两个尺寸设置为相等,因此组件不会收缩。然而,摆脱省略号是另一回事。