Here you can find the source of stringByTruncatingToFitInWidth(String s, int width, Graphics g, String truncatedSuffix)
Parameter | Description |
---|---|
s | String to truncate |
width | Width to fit string in |
g | Graphics object used to test string length |
truncatedSuffix | Suffix to append onto the string if it is truncated |
public static String stringByTruncatingToFitInWidth(String s, int width, Graphics g, String truncatedSuffix)
//package com.java2s; /******************************************************************************* * Copyright 2012 Geoscience Australia/*from w w w.j a va 2s .c om*/ * * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ import java.awt.Graphics; import java.awt.geom.Rectangle2D; public class Main { /** * Truncate a string until it fits in the given width. Tests string with * using the {@link FontMetrics} in the given {@link Graphics} object. * * @param s * String to truncate * @param width * Width to fit string in * @param g * Graphics object used to test string length * @param truncatedSuffix * Suffix to append onto the string if it is truncated * @return String that fits within the width. Returns null if null is * passed, or returns a blank string if no string will fit within * the given width. */ public static String stringByTruncatingToFitInWidth(String s, int width, Graphics g, String truncatedSuffix) { if (s == null) return null; if (truncatedSuffix == null) truncatedSuffix = ""; int length = s.length(); String truncated = s; while (length > 0) { Rectangle2D r = g.getFontMetrics().getStringBounds(truncated, g); if (r.getWidth() <= width) { return truncated; } length--; truncated = s.substring(0, length) + truncatedSuffix; } return ""; } }