Getting line count of wrapped text in JTextArea

I'm trying to get the line count of wrapped text in a JTextArea, but I see no way to do it other than to write a function for manually determining the line count, which I'm struggling with. I'm trying to get the following code to print out "4 4" on both lines, but it's printing out "1 1" instead. Is there a built-in way to get the actual line count? I'm guessing the JTextArea.getLineCount() function is supposed to count line breaks, which I don't have.
public class SSCCE
     public static void main(String args[])
          String s = "abc def ghi jkl mno pqr stu vwx yz1 234 567 890";
          JFrame f = new JFrame("test");
          JPanel p = new JPanel();
          JTextArea t[] = {cta(s,1,3),cta(s,1,4)};
          p.add(t[0]);
          p.add(t[1]);
          f.setSize(500,500);
          f.add(p);
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.setVisible(true);
          try
               Thread.sleep(200);
          catch (InterruptedException e)
               e.printStackTrace();
          System.out.println(t[0].getRows()+" "+t[1].getRows());
          System.out.println(t[0].getLineCount()+" "+t[1].getLineCount());
}

Oh wait, I see. Never mind. I went back there and saw that there were indeed two (last time I checked, I looked for the first one I saw since you didn't give me the full signature), and I got the one for the JTextArea, but I still need Thread.sleep to get the accurate line count.
import java.awt.Font;
import java.awt.KeyboardFocusManager;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.View;
public class SSCCE implements Runnable
     private static JTextArea t = cta("abc def ghi jkl mno pqr stu vwx yz1 234 567 890");
     public SSCCE()
          SwingUtilities.invokeLater(this);
          try
               SwingUtilities.invokeAndWait(this);
          catch (InterruptedException e){
               // TODO Auto-generated catch block
               e.printStackTrace();
          catch (InvocationTargetException e){
               // TODO Auto-generated catch block
               e.printStackTrace();
     @Override
     public void run()
          System.out.println(t.getLineCount());
     public static JTextArea cta(String text)
          JTextArea ta = new JTextArea(text,4,12);
          ta.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
          ta.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
          ta.setFont(new Font("Courier New",Font.PLAIN,12));
          ta.setLineWrap(true);
          ta.setWrapStyleWord(true);
          return ta;
     public static int getWrappedLines(JTextArea component)
          return (int)component.getUI().getRootView(component).getView(0).getPreferredSpan(View.Y_AXIS)/component.getFontMetrics(component.getFont()).getHeight();
     public static void main(String args[])
          JFrame f = new JFrame("Text Area Lines");
          JPanel p = new JPanel();
          p.add(t);
          f.add(p);
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.setSize(200,200);
          f.setLocationRelativeTo(null);
          f.setVisible(true);
          System.out.println(getWrappedLines(t));
          try
               Thread.sleep(50);
          catch(Exception e)
          System.out.println(getWrappedLines(t));
}Although, it's not working exactly the way I want it to. Is there a way to get this to work before I paint? It works fine after I paint, but I was just wondering.

Similar Messages

  • JLabel - calculating the number of lines in HTML wrapped text

    Hi folks,
    I've run into a problem. I have a JTable with row and column headers embedded within a JScrollPane. I have this component sized just how I like it. What I want to do is add a label above it serving as a title to the chart. I want this title to respect the width of the table - in other words, if the text within it is too long, I want it to wrap rather than to enlarge the size of the Table to fit it.
    I found that wrapping the title in "<html><center></center></html>" tags takes care of the wrapping. And furthermore I found code to handle the "dimension" of said label.
         * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4348815
        class WrappableJLabel extends JLabel {
               private final int preferredWidth;
               public WrappableJLabel(final int preferredWidth)
                  this.preferredWidth=preferredWidth;
               @Override
               public Dimension getPreferredSize()
                  Dimension superPreferred=super.getPreferredSize();
                  return new Dimension
                      (int) Math.min(preferredWidth,superPreferred.getWidth()),
                      (int) superPreferred.getHeight()
        }The problem is that the height does not get calculated correctly for the label. If I knew how many lines the JLabel's text took up, then I could multiply the height returned by the getPreferredSize() method by that number and get the correct size. I need to do all of this at compile time (so calling getHeight() on label doesn't help) so that I can size the JPanel holding both my table and my label to be of the correct size.
    Does anyone have any clues on how to do this?
    Thank you

    Maybe you need to calculate it yourself. The Java Developers Almanac 1.4 contains an general example:
    [http://www.exampledepot.com/egs/java.awt/TextDim.html|http://www.exampledepot.com/egs/java.awt/TextDim.html]
    You can obtain the font with the getFont() method on any component.

  • Way to get line count from text areas?

    the getLineCount method on JTextArea only returns the number of linebreak characters in the stream, but I am looking to get the number of rows the text is taking in the text area. When you have word wrap activated, and the text wraps around, no linebreak is inserted so the getLineCount method will return a wrong number. anyway to get around this?

    http://forum.java.sun.com/thread.jsp?forum=57&thread=122550

  • Problem with getting word count in TLF text

    Hi,
    I want to get the word count from my TLF text, but the problem is that I am not being able to handle th case for space.
    I am using the findNextWordBoundary property of ParagraphElement as shown below:
    private function countWords( para : ParagraphElement ) : void
                var wordBoundary:int = 0;
                var prevBoundary:int = 0;
                while ( wordBoundary != para.findNextWordBoundary( wordBoundary ) )
                   // If the value is greater than 1, then it's a word, otherwise it's a space.
                    if ( para.findNextWordBoundary( wordBoundary ) - wordBoundary > 1)
                        wordCount += 1;                   
                    prevBoundary = wordBoundary;
                    wordBoundary = para.findNextWordBoundary( wordBoundary );                   
                    // If the value is greater than 1, then it's a word, otherwise it's a space.
                    if ( wordBoundary - prevBoundary > 1 )
                        var s:String = para.getText().substring( prevBoundary, wordBoundary );
                        lenTotal += s.length;
    Now I have 2 issues here:
    If my string is for eg: Hi, I am writing in "TLF". And I want to get its word count then
    1) Suppose I take the case of the string Hi,  . Then para.getText().substring( prevBoundary, wordBoundary ) gives the text as Hi i.e without the comma. Same case for the string "TLF forums" , It treats each " as a single word and not the whole "TLF" as a single word. Why doesn't it compute till spaces, that should be the ideal case. So until we don't give a space it should count the whole thing as a word.
    2) So now the problem is I have applied a condition   if ( wordBoundary - prevBoundary > 1 ) to check if it is a space i.e. if the diff is <= 1 it is a Space. But if I use this I miss out on single words. Like for eg if I have "Hi, This is a string" ,then 'a' is ignored too.
    Now I could have added a check here along with the space check that the string between prevBoundary and wordBoundary is " "(i.e a space), Then also it is a problem as then the single words like a,&,I will be ignored.
    So, now I am stuck with this issue and need some help from you guys.
    Thanks

    findNextWordBoundary is not going to serve your purpose.  I'd propose doing something like this:
    // didn't test this but something like this - whitespace matches any set of 1 or more white space characters
    static const whiteSpaceRegExp:RegExp = /[u0020|u000A|u000D]*/
    public static function countWords( para : ParagraphElement ) : void
         return para.getText().split(whiteSpaceRegExp).length;
    A good list of everything considered whitespace extracted from the unicode space can be found here:
    http://sourceforge.net/adobe/tlf/svn/449/tree/trunk/textLayout/src/flashx/textLayout/utils /CharacterUtil.as
    In function createWhiteSpaceObject
    Hope that helps,
    Richard

  • Determine line count with wordwrap without Textcomponent visible

    Hi,
    I read a lot of post here that contains code that return number of line occupied by a wrapped text in JTextArea/JTextPane.
    However, the code only work if the text component is visible and already on screen.
    What I want is calculate the number of line count of wrapped text in those component even before the component is visible.
    Currenly, the line count always return 0 because component yet to display on screen.
    Can someone tell me how to do this ? thanx.

    I've been struggling with this for JTextArea. This seems to work. tp is the JTextArea and I get width from the preferred size.
            public int getLines(float width) {
                View view = tp.getUI().getRootView(tp).getView(0);
                view.setSize(width, (float)Short.MAX_VALUE);
                int preferredHeight = (int)view.getPreferredSpan(View.Y_AXIS);
                int lineHeight = tp.getFontMetrics( tp.getFont() ).getHeight();
                return preferredHeight / lineHeight;
            }

  • How to detect Wrap Event in JtextArea ?

    Hi, I would like my JTextArea to send an Event when it automatically wraps the text in order to resize the Component and show all the text. I mean the component should have exactly the same number of lines than the wrapped text.
    Does anybody have an idea on how to create that WrapEvent?
    If I have to extend a class, which one?
    Thanks!
    Papa Chlob

    I have exactly the same issue. Did you find something useful in th meantime ?
    Thanks
    [email protected]

  • How to get logical JTextArea line count

    Hi,
    I would like to get the logical JTextArea line count. The existing
    getLineCount method returns the line count based on "\n", which
    is not what I want.
    Any ideas?
    Thanks,
    Pin

    I found the following solution in the forum and it works.
    I haven't tested for all cases though...
    public static int getLineCount (JTextArea _textArea)
    boolean lineWrapHolder = _textArea.getLineWrap();
    _textArea.setLineWrap(false);
    double height = _textArea.getPreferredSize().getHeight();
    _textArea.setLineWrap(lineWrapHolder);
    double rowSize = height/_textArea.getLineCount();
    return (int) (_textArea.getPreferredSize().getHeight() / rowSize);
    Thanks,
    Pin

  • Compare text in one cell to a range of cells, get interger count of values

    Hi there,
    Basically what I'd like to do is, as a value in one cell, compare the text in a second cell to a range of third cells, and get a count of "hits".
    EXACT(second,third) will compare two cells, return a boolean. How do I batch run EXACT, and force boolean values into integers.
    Conceptually:
    For each J2:J14;$X=$X+INT(EXACT(B2,$_);return $X
    Can this be done in Numbers?

    Nevermind; the following works:
    =COUNTIF(($J2:$J14),B1)

  • Wrapping Text to a New Line in a Single Text Field.

    I was wondering is it possible to conintue text in the same text field that runs out of space on a line to a new line in the same text field.  If this is possible could someone please advise.
    i.e:
    alot of text and random txt [ text box   
    text ] more txt on the next line.

    You need to check the checkbox "Allow multiple lines" in the Object properties.. You need to check the checkbox "Expand to Fit" for height in the Layout properties of the field.
    When you do this, you need to set the subform that wraps the TextField to Flowed. Otherwise the text will overlap on the fields below.
    Make sure you save the form as Dynamic PDF. Goto File menu -> Form Properties and choose Default tab. And select "Render PDF as"  Dynamic PDF.
    Hope this helps.
    Thanks
    Srini
    Added the image.. Message was edited by: Srini Dhulipalla

  • How to get file line count.

    Hey guys,
    How to get file line count very fast? I am using BufferedReader to readLine() and count. But when dealing with big file, say several GB size, this process will be very time consuming.
    Is there any other methods?
    Thanks in advace!

    What I'd do is you create an infofetcher, register a listener, implement gotMore() and have that scan for '\n'
    Some might suggest getting rid of the listener/sender pattern or use multiple threads to make ii faster. This might help a little, but only if your I/O is super-duper speedy.
    you are welcome to use and modify this code, but please don't change the package or take credit for it as your own work.
    InfoFetcher.java
    ============
    package tjacobs.io;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    * InfoFetcher is a generic way to read data from an input stream (file, socket, etc)
    * InfoFetcher can be set up with a thread so that it reads from an input stream
    * and report to registered listeners as it gets
    * more information. This vastly simplifies the process of always re-writing
    * the same code for reading from an input stream.
    * <p>
    * I use this all over
         public class InfoFetcher implements Runnable {
              public byte[] buf;
              public InputStream in;
              public int waitTime;
              private ArrayList mListeners;
              public int got = 0;
              protected boolean mClearBufferFlag = false;
              public InfoFetcher(InputStream in, byte[] buf, int waitTime) {
                   this.buf = buf;
                   this.in = in;
                   this.waitTime = waitTime;
              public void addInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        mListeners = new ArrayList(2);
                   if (!mListeners.contains(fll)) {
                        mListeners.add(fll);
              public void removeInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        return;
                   mListeners.remove(fll);
              public byte[] readCompletely() {
                   run();
                   return buf;
              public int got() {
                   return got;
              public void run() {
                   if (waitTime > 0) {
                        TimeOut to = new TimeOut(waitTime);
                        Thread t = new Thread(to);
                        t.start();
                   int b;
                   try {
                        while ((b = in.read()) != -1) {
                             if (got + 1 > buf.length) {
                                  buf = IOUtils.expandBuf(buf);
                             int start = got;
                             buf[got++] = (byte) b;
                             int available = in.available();
                             //System.out.println("got = " + got + " available = " + available + " buf.length = " + buf.length);
                             if (got + available > buf.length) {
                                  buf = IOUtils.expandBuf(buf, Math.max(got + available, buf.length * 2));
                             got += in.read(buf, got, available);
                             signalListeners(false, start);
                             if (mClearBufferFlag) {
                                  mClearBufferFlag = false;
                                  got = 0;
                   } catch (IOException iox) {
                        throw new PartialReadException(got, buf.length);
                   } finally {
                        buf = IOUtils.trimBuf(buf, got);
                        signalListeners(true);
              private void setClearBufferFlag(boolean status) {
                   mClearBufferFlag = status;
              public void clearBuffer() {
                   setClearBufferFlag(true);
              private void signalListeners(boolean over) {
                   signalListeners (over, 0);
              private void signalListeners(boolean over, int start) {
                   if (mListeners != null) {
                        Iterator i = mListeners.iterator();
                        InputStreamEvent ev = new InputStreamEvent(got, buf, start);
                        //System.out.println("got: " + got + " buf = " + new String(buf, 0, 20));
                        while (i.hasNext()) {
                             InputStreamListener fll = (InputStreamListener) i.next();
                             if (over) {
                                  fll.gotAll(ev);
                             } else {
                                  fll.gotMore(ev);
    InputStreamListener.java
    ====================
    package tjacobs.io;
         public interface InputStreamListener {
               * the new data retrieved is in the byte array from <i>start</i> to <i>totalBytesRetrieved</i> in the buffer
              public void gotMore(InputStreamEvent ev);
               * reading has finished. The entire contents read from the stream in
               * in the buffer
              public void gotAll(InputStreamEvent ev);
    InputStreamEvent
    ===============
    package tjacobs.io;
    * The InputStreamEvent fired from the InfoFetcher
    * the new data retrieved is from <i>start</i> to <i>totalBytesRetrieved</i> in the buffer
    public class InputStreamEvent {
         public int totalBytesRetrieved;
         public int start;
         public byte buffer[];
         public InputStreamEvent (int bytes, byte buf[]) {
              this(bytes, buf, 0);
         public InputStreamEvent (int bytes, byte buf[], int start) {
              totalBytesRetrieved = bytes;
              buffer = buf;
              this.start = start;
         public int getBytesRetrieved() {
              return totalBytesRetrieved;
         public int getStart() {
              return start;
         public byte[] getBytes() {
              return buffer;
    ParialReadException
    =================
    package tjacobs.io;
    public class PartialReadException extends RuntimeException {
         public PartialReadException(int got, int total) {
              super("Got " + got + " of " + total + " bytes");
    }

  • Get Record count and text of PreparedStatement

    Hi,
    Is it possible to get a count of the records returned in a ResultSet?
    Also, is it possible to get the text of a query(PreparedStatement). I am using a PreparedStatement, and want to know what the actual query looks like, with the parameters. i.e. Are the parameters being set correctly or not.
    Thanks,
    Dewang

    Is it possible to get a count of the records returned
    in a ResultSet?You will have to count them - I don't know of any other way.
    I am using a
    PreparedStatement, and want to know what the actual
    query looks like, with the parameters. i.e. Are the
    parameters being set correctly or not.You will have to use debugging statements (possibly on both sides - in the Java and in your stored procedures if you are using them). You have to assume that your JDBC driver is managing the conversions properly, as long as you match the data types right. It's really pretty straight-forward, just a little tedious.

  • Multiple small stories with variable line counts assigned to different editors

    I have a "best practice" question for you more experienced InCopy users about what workflow you recommend for my specific issue. I am experienced in InDesign, but am a InCopy newbie. I want to make sure I'm not missing a solution because my lack of experience with InCopy may be causing me not to see the forest for the trees.
    Short version: What is the best way to allow multiple editors access to each of multiple small stories separately (one story per editor), but to allow the line count of each story to be variable each week, while adjusting the rest of the stories along with it on the page (see image below)?
    Details: My publishing company's workflow is on CS6 with editors working in Word, and we're upgrading to CC2014 with InCopy. We have 7 in-house editors, and all files on an in-house server. We have quick deadlines (some are 15 minutes from editor writing copy to transmitting publication to subscribers). In the example below, we have 10 sections, and I have all seven editors writing different sections at the same time. A final editor has control over fitting the final page. My INDD files to test the new workflow use an assignment-based workflow. I understand I can place each of these sections as their own story, under the same assignment, so a different editor can have them checked out. However, each section does not have the same line count from week to week. Markets with more activity will get more lines.
    In our current workflow, we have multiple rough Word docs pulled into one master doc with a script, that the final editor edits to fit, so each section can be a different number of lines as long as the total is the same. Then production staff load it in. When we upgrade, we can use a hybrid workflow where the final editor just loads that final Word doc into one InCopy story and edits it to fit.
    It would be great if I just didn't understand how to make the text height variable for the story each editor is typing, and auto-adjust so the next story starts below where the story above it ends, and you all had an idea how I can do it!
    Thanks! Nancy

    I disagree to Seshu's answer to question 1.
    Correct answer of question 1 is C and <u><b>not A.</b></u>
    Sorry I didn't find time to check the rest.
    <u>To the examinee</u>
    I wouldn't assume all answers from SDN-ers are correct if my certification exam was knocking the door! I would rather try and find out the correct answers myself from the system instead of mugging these answers without any understanding of the technology involved! Find out the answers yourself from the system...that way it will help you to understand why the answer is 'C' and not 'A'...just knowing the answer is 'C' is not good enough...one has to understand "why" its 'C' and not 'A'. Hope you get my point! Good luck.

  • Wrap text for all-day events

    I've seen this question floating around, unanswered, since 2005...
    How can I get iCal to show the full text of an all-day event in Month View? There's lots of blank white space, but it seems that iCal never wraps the text of all-day events, and just cuts off the text that doesn't fit on one line.
    Am I missing something? Is there any way to get Apple to implement something so basic?

    I have the same question, but need to add one odd observation about my own experience...
    When I enter new events, sometimes the text wraps to two lines and sometimes the text is cut off after one line. It appears to be about 50-50. I can find no explanation for this behavior anywhere nor any way to control it. Very strange.

  • Looking for a word processor without word wrap, text edit doesn't cut it

    I'm looking for a word processor without word wrap, text edit doesn't work. In text edit, it automatically scoots my text over to the next line but I just want it to keep going with a horizontal scrollbar. Is there a text editor I can download from the app store or can I get textedit to work somehow where it uses a horizontal scroll bar instead of entering text to the next line?

    Hi,
    thought TextWrangler can do it.
    But it seems that the 'no word-wrap' "feature" isn't that much wanted anymore.
    Maybe one of these http://www.macupdate.com/find/mac/text%20editor can do it.
    Regards
    Stefan

  • How do you get word count to print at the end of a document in Pages?

    How do you get word count to print at the end of a document in Pages?

    Pages v5 does not provide a user assignable word count variable. With some AppleScript, and a paste operation from the clipboard, you can have locale punctuated word count in this format: 7,803 — anywhere in your document. The following AppleScript works with Pages '09 v4.3 through Pages v5.5.2 on Yosemite.
    I would suggest that you copy paste the following AppleScript into your [Apple] Script Editor and save it (suggestion) wordcnt.applescript. Then, follow this with an option+Save As… and this time set the File format to Script Bundle, or Application with hidden extension — saved to your Desktop. Provided you have a Pages document open, you are then a double-click from the ability to paste your current word count into Pages.
    Note: If you have Pages word count display enabled, it will automatically count your pasted value as another word which initially may deceive on true word count at the time the script was run.
    AppleScript
    --- copy below this line ---
    property locale : "en_US.UTF-8" -- In Terminal, use the locale command to see yours
    if not ApplicationIsRunning("Pages") then
         display dialog "Pages must be running to use this utility."
         return quit
    end if
    tell application "Pages"
        tell body text of front document
            set wordCnt to count words
            -- Don't want punctuated numbers? Remove the single quote from printf format
            set the clipboard to (do shell script "export LC_ALL=" & locale & "; printf \"%'d\" " & wordCnt)
        end tell
    end tell
    on ApplicationIsRunning(appName)
         tell application "System Events" to set appNameIsRunning to exists (processes where name is appName)
         return appNameIsRunning
    end ApplicationIsRunning

Maybe you are looking for