How to programmatically know when JButton text is truncated?

I need to know when the text for the JButton is truncated by the layout. So, to find out that I'm overriding the following method in our custom ButtonUI debit:

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

      

Inside the method, I check if the text argument ends with an ellipse.

Is there a better way to check if the text is truncated? How about an ellipse? Is this a wildcard for truncated text, or do I need to search for localized characters that will delimit the truncated text?

I noticed that OSX will use one character to represent an ellipse and Windows will use three periods. I guess this is font based, but it got me thinking about other things that might be sneaking up on me.

Thank.

+2


source to share


3 answers


Wouldn't this work if you compare the text passed to your method paintText

with the text returned from ((AbstractButton)c).getText()

? If it is different, the text has been truncated.



After all, the truncation itself is done in SwingUtilities.layoutCompoundLabel

, and you can call this method yourself, but it is not very easy to compute all the arguments required to directly use this method.

+2


source


I've put together a small app to demonstrate how you can figure this out. In mine, the JButton

meat is in the override method getToolTipText()

. It checks the size of the button by composing the right and left padding depending on the size of the text using "FontMetrics". If you run the demo you can resize the window and hover over to try to get a hint. I only have to show if there is an ellipsis. Here is the code:



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


source


I would guess that the ellipse will be shown when

getPrefferredSize().width > getSize().width

      

+1


source







All Articles