Used for cutting off text that is too wide. - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

Used for cutting off text that is too wide.

Demo Code


//package com.java2s;

import java.awt.FontMetrics;

public class Main {
    /**   Used for cutting off text that is too wide.
       @param font The FontMetrice displaying the string
       @param s The String to be displayed
       @param width The cutoff width/*w ww  .  j a v a 2 s.  com*/
       @return The string cut to fit into the width with "..." added to the end.
     */
    private static String clip(FontMetrics font, String s, int width) {
        if (font.stringWidth(s) <= width)
            return s;
        else {
            String clip = s.substring(0, s.length() - 1);

            while (font.stringWidth(clip + "...") > width
                    && clip.length() > 0)
                clip = clip.substring(0, clip.length() - 1);

            return clip + "...";
        }
    }
}

Related Tutorials