2013-10-15 113 views
0

我有一个JTextField,它的大小可能因分辨率而异。 JTextField将保存一个3个字母的字符串。最大化字体大小,同时保持文本在JTextField中

我想以这种方式设置JTextField的字体大小,使字体大小最大化,同时使JTextField中的文本FIT仍然完美。

有没有一个算法来做到这一点?

+2

'JTextField#setColumns' – MadProgrammer

+0

为什么? (15个字符) – kleopatra

回答

0

我用的Martijn的答案,用下面的答案一起:

String length in pixels in Java

Java: Getting a font with a specific height in pixels

...为了写一个完整的回答我的问题。在这里。感谢所有贡献者。

您需要导入以下:

import javax.swing.JTextField; 
import java.awt.Font; 
import java.awt.image.BufferedImage; 
import java.awt.FontMetrics; 
import java.lang.Math; 

............................... ...

public int getFontSize(JTextField text, int columnsToHold){ 
      //Create a sample test String (we will it later in our calculations) 
      String testString = ""; 
      for(int i = 0; i<columnsToHold; i++){ 
        testString = testString + "5"; 
      } 


      //size will hold the optimal Vertical point size for the font 
     Boolean up = null; 
     int size = text.getHeight(); 
     Font font; 
    while (true) { 
     font = new Font("Default", 0, size); 
     int testHeight = getFontMetrics(font).getHeight(); 
     if (testHeight < height && up != Boolean.FALSE) { 
      size++; 
      up = Boolean.TRUE; 
     } else if (testHeight > height && up != Boolean.TRUE) { 
      size--; 
      up = Boolean.FALSE; 
     } else { 
      break; 
     } 
    } 
     //At this point, size holds the optimal Vertical font size 

     //Now we will calculate the width of the sample string 
    BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); 
    FontMetrics fm = img.getGraphics().getFontMetrics(font); 
    int width = fm.stringWidth(testString); 

     //Using Martijn's answer, we calculate the optimal Horizontal font size 
    int newFontSize = size * textos[0].getWidth()/width; 

     //The perfect font size will be the minimum between both optimal font sizes. 
     //I have subtracted 2 from each font so that it is not too tight to the edges 
    return Math.min(newFontSize-2, size-2); 
} 
+0

使用'Toolkit.getDefaultToolkit()。getFontMetrics(font);'代替。 –

2

由于字体大小为a的字符串的宽度为x。可用空间为s。那么你可以显然扩大你的字体因子:s/x。所以选择a * s/x作为字体大小。要知道x,请使用任意字体大小a来计算字符串的宽度。

+0

谢谢。这有助于我根据JTextField宽度进行尺寸调整。但是,我确实需要考虑JTextField的高度,或根据垂直轴的大小。 – ThePrince

+0

虽然我已upvoted。我想我会稍微扩展你的答案并发布它 – ThePrince