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 check compares the component’s actual width (its width property) with the width needed to display the whole text, including the component’s insets (border and margin). If the component is too narrow, the script calls Squish’s test.fail().

The check compares the component’s actual width (its width property) with the width needed to display the whole text, including the component’s insets (border and margin). If the component is too narrow, the script calls Squish’s test.fail().

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 + " The text is truncated")
    else:
        test.passes(msg + " The text is NOT truncated")

def is_truncated_swing(obj, text):
    font_metrics = obj.getFontMetrics(obj.font)
    insets = obj.getInsets()
    needed = font_metrics.stringWidth(text) + insets.left + insets.right
    return obj.width < needed

Java 9 and later

On Java 9 and later, the script fails with an error like this:

RuntimeError: Error in stringWidth() invocation: exception: java.lang.IllegalAccessException:
class com.froglogic.squish.awt.AWT cannot access class sun.font.FontDesignMetrics
(in module java.desktop) because module java.desktop does not export sun.font to unnamed module

getFontMetrics() returns an instance of an internal JDK class, sun.font.FontDesignMetrics. Since Java 9, the module system blocks reflective access to internal packages, and Squish calls stringWidth() through reflection.

To fix this, start the application with the following JVM option:

--add-exports java.desktop/sun.font=ALL-UNNAMED

For example:

java --add-exports java.desktop/sun.font=ALL-UNNAMED -jar MyApp.jar

In Squish, add the option to the AUT’s arguments in the test suite settings, before -jar or the main class name.