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



有很多关于这个问题的帖子,但我无法理解那里的人给出的答案。就像这篇文章一样:"如何更改 JLabel 字体的大小以采用最大大小"答案将字体大小转换为 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;//DEBUG TRY

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

编自您提到的问题的答案:

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部分(。

编辑:如果您不能/不想保留对原始字体的引用,则可以将其另存为"客户端属性"(请参阅第一行(。

最新更新