Here you can find the source of getTextDimension(JTextArea textArea, Dimension maxDimension)
Parameter | Description |
---|---|
textArea | specified text area |
maxDimension | maximum dimension to be used |
public static Dimension getTextDimension(JTextArea textArea, Dimension maxDimension)
//package com.java2s; // it under the terms of the GNU General Public License as published by import javax.swing.*; import java.awt.*; import java.util.StringTokenizer; public class Main { private static final int wPadding = 30; private static final int hPadding = 2; /**/*from w ww . j a va2s . co m*/ * @param textArea specified text area * @param maxDimension maximum dimension to be used * @return the specified text dimension to be displayed */ //=============================================================== public static Dimension getTextDimension(JTextArea textArea, Dimension maxDimension) { Font font = textArea.getFont(); // get metrics from the graphics FontMetrics metrics = textArea.getGraphics().getFontMetrics(font); int width = metrics.stringWidth(getLongestLine(textArea.getText())) + wPadding; int height = (metrics.getHeight() + hPadding) * countLines(textArea.getText()); if (width > maxDimension.width) width = maxDimension.width; if (height > maxDimension.height) height = maxDimension.height; return new Dimension(width, height); } private static String getLongestLine(String text) { StringTokenizer stk = new StringTokenizer(text, "\n"); int max = 0; String str = ""; while (stk.hasMoreTokens()) { String s = stk.nextToken(); int length = s.length(); if (length > max) { max = length; str = s; } } return str; } private static int countLines(String str) { StringTokenizer stk = new StringTokenizer(str, "\n"); return stk.countTokens(); } }