2013-10-15 3 views
0

해상도에 따라 크기가 다를 수있는 JTextField가 있습니다. JTextField는 3 자 문자열을 보유합니다.JTextField 내에 텍스트를 유지하면서 글꼴 크기 최대화

JTextField 내부에 텍스트 FIT가있는 동안 글꼴 크기를 MAXIMIZE하는 방식으로 JTextField의 글꼴 크기를 설정하고 싶습니다.

이렇게하는 알고리즘이 있습니까?

+2

'JTextField # setColumns' – MadProgrammer

+0

왜? (15 자) – kleopatra

답변

0

나는 다음과 같은 답변과 함께, 마티의 답변을 사용하고 있습니다 :

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을 fontsize로 선택하십시오. x을 알고 싶다면 임의의 글꼴 크기 a으로 문자열의 너비를 계산하십시오.

+0

고맙습니다. JTextField 너비에 따라 크기 조정에 도움이됩니다. 그러나 JTextField 높이 또는 세로 축에 따라 크기를 고려해야합니다. – ThePrince

+0

나는 upvoted했다. 나는 당신의 대답을 조금 더 확장하고 게시 할 것입니다. – ThePrince