使用MigLayout的paint()中的setFont不要调整容器的大小

时间:2014-08-09 19:48:00

标签: java swing layout-manager miglayout

我正在尝试在MigLayout中编写一个包含3个垂直剖面的面板:顶部增长,中间固定和底部增长。

顶部是一个font-size-based-on-container-size的JLabel。中间也是一个Jlabel,底部是一个空的JPanel。

放大窗口没问题: Enlarging window

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

只有在重载方法paint(见下文)在计时器JLabel上调用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。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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

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