Here you can find the source of clipString(JComponent c, FontMetrics fm, String string, int availTextWidth)
Parameter | Description |
---|---|
c | JComponent that will display the string, may be null |
fm | FontMetrics used to measure the String width |
string | String to display |
availTextWidth | Amount of space that the string can be drawn in |
public static String clipString(JComponent c, FontMetrics fm, String string, int availTextWidth)
//package com.java2s; /*/* w w w .j a va 2s . c o m*/ * ?Copyright (C) 2013 Atlas of Living Australia * All Rights Reserved. * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ import java.awt.FontMetrics; import javax.swing.JComponent; public class Main { /** * Clips the passed in String to the space provided. NOTE: this assumes the string does not fit in the available space. * * @param c * JComponent that will display the string, may be null * @param fm * FontMetrics used to measure the String width * @param string * String to display * @param availTextWidth * Amount of space that the string can be drawn in * @return Clipped string that can fit in the provided space. */ public static String clipString(JComponent c, FontMetrics fm, String string, int availTextWidth) { // c may be null here. String clipString = "..."; int width = stringWidth(c, fm, clipString); // NOTE: This does NOT work for surrogate pairs and other fun // stuff int nChars = 0; for (int max = string.length(); nChars < max; nChars++) { width += fm.charWidth(string.charAt(nChars)); if (width > availTextWidth) { break; } } string = string.substring(0, nChars) + clipString; return string; } /** * Returns the width of the passed in String. * * @param c * JComponent that will display the string, may be null * @param fm * FontMetrics used to measure the String width * @param string * String to get the width of */ public static int stringWidth(JComponent c, FontMetrics fm, String string) { return fm.stringWidth(string); } }