Here you can find the source of clipString(FontMetrics metrics, int availableWidth, String fullText)
Parameter | Description |
---|---|
metrics | Font metrics. |
availableWidth | Available width in pixels. |
fullText | String to clip. |
public static String clipString(FontMetrics metrics, int availableWidth, String fullText)
//package com.java2s; import java.awt.*; public class Main { /**/*from ww w . j a va 2s . co m*/ * Clips string based on specified font metrics and available width (in * pixels). Returns the clipped string, which contains the beginning and the * end of the input string separated by ellipses (...) in case the string is * too long to fit into the specified width, and the origianl string * otherwise. * * @param metrics * Font metrics. * @param availableWidth * Available width in pixels. * @param fullText * String to clip. * @return The clipped string, which contains the beginning and the end of * the input string separated by ellipses (...) in case the string * is too long to fit into the specified width, and the origianl * string otherwise. */ public static String clipString(FontMetrics metrics, int availableWidth, String fullText) { if (metrics.stringWidth(fullText) <= availableWidth) return fullText; String ellipses = "..."; int ellipsesWidth = metrics.stringWidth(ellipses); if (ellipsesWidth > availableWidth) return ""; String starter = ""; int w = fullText.length(); String prevText = ""; for (int i = 0; i < w; i++) { String newStarter = starter + fullText.charAt(i); String newText = newStarter + ellipses; if (metrics.stringWidth(newText) <= availableWidth) { starter = newStarter; prevText = newText; continue; } return prevText; } return fullText; } }