如果文本不适合JLabel,我想减小字体大小

时间:2013-10-05 06:20:26

标签: java swing fonts jlabel

关于这个问题有很多帖子,但我无法理解那里的人给出的答案。 就像在这篇文章中:“How to change the size of the font of a JLabel to take the maximum size”答案将字体大小转换为14!但这是静态的,在其他答案中也是如此;他们的整个输出屏幕似乎都在增加。

我在一个名为“lnum”的JLabel中显示某些数字,它可以显示最多3位数字,但之后它显示为“4 ...”我希望如果数字能够适合标签,它应该不改变它的字体大小,但如果数字是4位数,它应该以适合的方式减小字体大小。注意:我不希望jLabel的尺寸发生变化。我只是想改变它中的文字。

编辑: 这是我试过的代码

String text = lnum.getText();        
System.out.println("String Text = "+text);//DEBUG
Font originalFont = (Font)lnum.getClientProperty("originalfont"); // Get the original Font from client properties            
 if (originalFont == null) { // First time we call it: add it
        originalFont = lnum.getFont();
        lnum.putClientProperty("originalfont", originalFont);
    }
 int stringWidth = lnum.getFontMetrics(originalFont).stringWidth(text);       

 int componentWidth = lnum.getWidth();
 stringWidth = stringWidth + 25; //DEBUG TRY
 if (stringWidth > componentWidth) { // Resize only if needed
        // Find out how much the font can shrink in width.
        double widthRatio = (double)componentWidth / (double)stringWidth;

        int newFontSize = (int)Math.floor(originalFont.getSize() * widthRatio); // Keep the minimum size

        // Set the label's font size to the newly determined size.
        lnum.setFont(new Font(originalFont.getName(), originalFont.getStyle(), newFontSize));
    }else{
        lnum.setFont(originalFont); // Text fits, do not change font size
        System.out.println("I didnt change it hahaha");//DEBUG 
 }
    lnum.setText(text);

我有一个问题很多次它不起作用,就像文本是“-28885”它显示“-28 ......”。

stringWidth = stringWidth + 25; //调试尝试

我必须添加此代码,以便增加它获得的长度。这是我添加的代码,只是暂时修复问题。我想要一个永久的解决方案。

1 个答案:

答案 0 :(得分:2)

改编自an answer on the question you referred to

void setTextFit(JLabel label, String text) {
    Font originalFont = (Font)label.getClientProperty("originalfont"); // Get the original Font from client properties
    if (originalFont == null) { // First time we call it: add it
        originalFont = label.getFont();
        label.putClientProperty("originalfont", originalFont);
    }

    int stringWidth = label.getFontMetrics(originalFont).stringWidth(text);
    int componentWidth = label.getWidth();

    if (stringWidth > componentWidth) { // Resize only if needed
        // Find out how much the font can shrink in width.
        double widthRatio = (double)componentWidth / (double)stringWidth;

        int newFontSize = (int)Math.floor(originalFont.getSize() * widthRatio); // Keep the minimum size

        // Set the label's font size to the newly determined size.
        label.setFont(new Font(originalFont.getName(), originalFont.getStyle(), newFontSize));
    } else
        label.setFont(originalFont); // Text fits, do not change font size

    label.setText(text);
}

当您显示适合的数字时,您应该将字体重置为原始数字(请参阅else部分)。

编辑:如果你不能/不想保留对原始字体的引用,可以将其保存为“客户端属性”(参见第一行)。

相关问题