2009-10-05 23 views
2

我需要知道何時JButton的文本被佈局截斷。因此,爲了找出我重寫下面的方法在我們的定製ButtonUI委託:如何以編程方式知道JButton的文本何時被截斷?

protected void paintText(Graphics g, JComponent c, Rectangle textRect, String text) { 
    //the text argument will show an ellipse (...) when truncated 
} 

裏面我檢查,看看是否文本參數與橢圓結束的方法。

有沒有更好的方法讓我檢查文本是否被截斷?那橢圓呢?這是截斷文本的通用符號,還是我需要查找將劃分截斷文本的本地化符號?

我注意到OSX將使用代表橢圓的單個字符,Windows將使用三個週期。我認爲這是基於正在使用的字體,但它讓我想到其他可能潛入我的東西。

謝謝。

回答

2

如果您將傳遞給您的paintText方法的文本與從((AbstractButton)c).getText()返回的文本進行比較,將會不起作用嗎?如果不同,文本已被截斷。

最終,截斷本身在SwingUtilities.layoutCompoundLabel中完成,您可以自己調用該方法,但直接使用該方法計算所需的所有參數似乎並不容易。

+0

我喜歡這個解決方案。我可以停止尋找一個橢圓形,只要文本不同就顯示工具提示。 – 2009-10-07 12:58:16

1

我已經放在一起的一個小應用程序來演示如何解決它。肉是在我的JButton覆蓋​​方法。它使用'FontMetrics'來測試按鈕的大小,並考慮右邊和左邊的插圖,與文本的大小。如果運行演示,您可以調整窗口大小並將鼠標懸停在試圖獲取工具提示上。我應該只顯示是否有省略號。下面是代碼:

public class GUITest { 
    JFrame frame; 
    public static void main(String[] args){ 
     new GUITest(); 
    } 
    public GUITest() { 
     frame = new JFrame("test"); 
     frame.setSize(300,300); 
     addStuffToFrame(); 
     SwingUtilities.invokeLater(new Runnable(){ 
      public void run() { 
       frame.setVisible(true); 
      } 
     }); 
    }  

    private void addStuffToFrame() {  
     JPanel panel = new JPanel(); 
     JButton b = new JButton("will this cause an elipsis?") { 
      public String getToolTipText() { 
       FontMetrics fm = getFontMetrics(getFont()); 
       String text = getText(); 
       int textWidth = fm.stringWidth(text); 
       return (textWidth > (getSize().width - getInsets().left - getInsets().right) ? text : null); 
      } 
     }; 
     ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); 
     toolTipManager.registerComponent(b); 
     frame.setContentPane(b); 
    } 


} 
+1

這種方法太天真了,至少對於通用功能來說。如果按鈕顯示圖標以及圖標和文本之間的間隙,它不會考慮按鈕的內嵌(文本週圍的內部邊框)。如果文本包含HTML標記,它也會失敗。 – jarnbjo 2009-10-05 23:14:15

1

我猜想,ellispse將顯示,當

getPrefferredSize().width > getSize().width 
相關問題