2012-09-20 30 views
0

我有一個SWT標籤,顯示從文件加載的不同單行文本。有沒有一種方法可以自動調整字體大小,以便在長文本出現時字體大小變小並且標籤仍然顯示全文? 當Label沒有這樣的屬性時,是否可以使用字體和字體大小來計算字符串的大小?java標籤automatic fontsize

回答

0

這裏是我的理解。您的標籤寬度是固定的(假設爲200)。您讀取的字符串需要300個像素以適合當前的字體。您可以通過使用GC.textExtent(String)

計算得出所需要的尺寸試試這個工作示例

private static boolean setText(Label label, String txt, Font font) 
    { 

    int height = font.getFontData()[0].getHeight(); 
    GC gc = new GC(label); 
    gc.setFont(font); 
    Point size = gc.textExtent(txt); 
    Rectangle bounds = label.getBounds(); 
    int diff = bounds.width-size.x; 
    if(diff >= 0 || height <=2) 
    { 
     label.setFont(font); 
     label.setText(txt); 
     return true; 
    } 
    else 
    { 

     String name = font.getFontData()[0].getName(); 
     int style = font.getFontData()[0].getStyle(); 
     FontData data = new FontData(name, Math.max(1,height-1), style); 
     Font newFont = new Font(Display.getCurrent(), data); 
     if(!setText(label, txt, newFont)) 
     { 
     newFont.dispose(); 
     } 
    } 
    gc.dispose(); 
    return false; 
    } 

    public static void main(String[] args) { 



    Display display = new Display(); 
    final Shell shell = new Shell(display); 
    shell.setSize(600, 300); 

    Label label = new Label(shell, SWT.NONE); 
    label.setBounds(20, 20, 100, 50); 
    setText(label, "hello stackoverflow!!!!!!", Display.getDefault().getSystemFont()); 
    shell.open(); 


    while (!shell.isDisposed()) { 
     if (!display.readAndDispatch()) 
     display.sleep(); 
    } 
    display.dispose(); 


    } 
+0

偉大的解決方案!謝謝 – boreas