How can I crop strings in Java2D and add ... at the end?

I am trying to print invoices in Java Swing applications. I do this by expanding Printableand implementing the method public int print(Graphics g, PageFormat pf, int page).

I would like to draw rows in columns, and when the row is long, I want her clip and let it end with "...". How to measure a line and copy it to the desired position?

Some of my code:

Font headline = new Font("Times New Roman", Font.BOLD, 14);
g2d.setFont(headline);
FontMetrics metrics = g2d.getFontMetrics(headline);
g2d.drawString(myString, 0, 20);

Ie How can I limit the myStringmaximum to 120px?

I could use metrics.stringWidth(myString), but I do not get the position where I need to pin the string.

Expected results may be:

A longer string that exc...
A shorter string.
Another long string, but OK
+3
source share
3 answers

, stringWidth, , . , , . ( ...) ... .

, - , . , WWWWWWWWiiiiii, , , . .

+1

, , , , , elipsis.

, N-1 chars, N-2, N-3 .., + "...", . , , , .

0
String cutString(String originalString, int placeholderWidth, FontMetrics fontMetrics) {
    int stringWidth = fontMetrics.stringWidth(originalString);
    String resultString = originalString;

    while (stringWidth >= placeholderWidth) {
        resultString = resultString.substring(0, resultString.length() - 4);
        resultString = resultString.concat("...");
        stringWidth = fontMetrics.stringWidth(resultString);
    }

    return resultString;
}
-1
source

Source: https://habr.com/ru/post/1745789/


All Articles