1. 程式人生 > >swing獲取固定畫素長度的字串

swing獲取固定畫素長度的字串

/*
	 * strValue: 需要擷取的字串 擷取固定畫素長度的字串
	 */
	
	public String trimDownText(String strValue)
	{
		// jLabelName放置字串的控制元件(JLabel jLabelName = new JLabel();)
		int width = jLabelName.getWidth();
		if (getLength(strValue) <= width)
		{
			return strValue;
		}
		else
		{
			char[] chars = strValue.toCharArray();
			StringBuilder builder = new StringBuilder();
			for (int i = 0; i < chars.length; i++)
			{
				builder.append(chars[i]);
				// 一個省略號3個畫素,最後追加三個省略號
				if (getLength(builder.toString()) > width - 9)
				{
					return builder.append("...").toString();
				}
			}
		}
		return cutStr(strValue, 20);
	}
	/**
	 * 獲取畫素長度
	 * @param strValue
	 * @return
	 */
	private int getLength(String strValue)
	{
		FontMetrics fm = jLabelName.getFontMetrics(UiStyle.FONT_12);
		Rectangle2D bounds = fm.getStringBounds(strValue, null);
		return (int) bounds.getWidth();
	}
	
	/**
	 * 返回擷取指定長度位元組數後的字串,多餘部分用“...”代替
	 * 
	 * @作者 jiyanle
	 * @日期 2014-7-6
	 * @param strs
	 * @param length
	 * @return
	 */
	private String cutStr(String strs, int length)
	{
		int sum = 0;
		String finalStr = "";
		if (null == strs || strs.getBytes().length <= length)
		{
			finalStr = (strs == null ? "" : strs);
		}
		else
		{
			for (int i = 0; i < strs.length(); i++)
			{
				String str = strs.substring(i, i + 1);
				// 累加單個字元位元組數
				sum += str.getBytes().length;
				if (sum > length)
				{
					finalStr = strs.substring(0, i) + "...";
					break;
				}
			}
		}
		return finalStr;
	}