Java JTextArea getTextDimension(JTextArea textArea, Dimension maxDimension)

Here you can find the source of getTextDimension(JTextArea textArea, Dimension maxDimension)

Description

get Text Dimension

License

Open Source License

Parameter

Parameter Description
textArea specified text area
maxDimension maximum dimension to be used

Return

the specified text dimension to be displayed

Declaration


public static Dimension getTextDimension(JTextArea textArea, Dimension maxDimension) 

Method Source Code


//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();
    }
}

Related

  1. display(JTextArea txtOutput, String text)
  2. estimatedRows(JTextArea text)
  3. fixTabKeys(JTextArea textArea)
  4. getAreaValue(JTextArea ta)
  5. getTextAreaScrollPaneContainer(JTextArea textArea, int nbLines)
  6. initLogConsole(final JTextArea textArea)
  7. initTextAreaEdit(JTextArea j1)
  8. makeLabelStyle(JTextArea textArea)
  9. makeTabMoveFocus(JTextArea textArea)