Check for truncation of displayed text (Java, Swing)

Last edited on

This example shows how to check whether the text shown in a JComponent (or a subclass of JComponent) has been truncated (e.g., because it is wider than the width of the GUI control).

The is_truncated_swing() function compares the widget’s actual width (from its width property), with the number of pixels needed to display the entire text (returned by the requiredWidth() function), and calls Squish’ test.fail() function if the actual width is less than the required width.

def main():
    n = {'caption':'Backspace', 'type':'javax.swing.JButton', 'visible':True}
    o = waitForObject(n)
    msg = "Truncation check: Object: %s: Text: %s " % (n, o.text)
    if is_truncated_swing(o, o.text):
        test.fail(msg)
    else:
        test.passes(msg)

def is_truncated_swing(obj, text):
    font_metrics = obj.getFontMetrics(obj.font)
    return obj.width <= font_metrics.stringWidth(text)