Java Swing Font Metrics getClippedText(String text, FontMetrics fm, int maxWidth)

Here you can find the source of getClippedText(String text, FontMetrics fm, int maxWidth)

Description

get Clipped Text

License

Open Source License

Declaration

public static String getClippedText(String text, FontMetrics fm, int maxWidth) 

Method Source Code

//package com.java2s;
/*/* ww w . j  a va 2 s  .  c om*/
 * DataViewerUtilities.java  2/6/13 1:04 PM
 *
 * Copyright (C) 2012-2013 Nick Ma
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

import java.awt.*;

import javax.swing.*;

public class Main {
    private static final String ELLIPSIS = "...";

    public static String getClippedText(String text, FontMetrics fm, int maxWidth) {
        if ((text == null) || (text.length() == 0)) {
            return "";
        }
        int width = SwingUtilities.computeStringWidth(fm, text);
        if (width > maxWidth) {
            int totalWidth = SwingUtilities.computeStringWidth(fm, ELLIPSIS);
            for (int i = 0; i < text.length(); i++) {
                totalWidth += fm.charWidth(text.charAt(i));
                if (totalWidth > maxWidth) {
                    return text.substring(0, i) + ELLIPSIS;
                }
            }
        }
        return text;
    }
}

Related

  1. clipText(FontMetrics fm, String val, int width)
  2. computeMultiLineStringDimension(FontMetrics oFontMetrics, String[] astr)
  3. computeStringWidth(FontMetrics fontMetrics, String str)
  4. drawLine(Graphics g, FontMetrics fm, Rectangle rect, String text, int hAlign, int y, int mnemonic)
  5. getBreakLocation(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset)
  6. getClippedText(String text, FontMetrics fm, int maxWidth)
  7. getClippedText(String text, FontMetrics fm, int maxWidth)
  8. getDefaultLabelFontMetrics()
  9. getFontMetrics(final JComponent c, final Graphics g)