Word count and my ActionPerformed

I am having a little trouble with my program and was wondering if anyone could spot the mistake... I am trying to make a simple application that will count the number of words in a text field via click of a button and display the results.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class WordCount extends JFrame implements ActionListener
// added JTextPane, JScrollPane, JPanel JTextField, and JButton
    public static void main(String[] args)
     // layout
    public WordCount()
          super();
          Container cp = getContentPane();
          wordCount.setEditable(false);
          south.setLayout(new FlowLayout(FlowLayout.CENTER));
          south.add(jbtCount);
               jbtCount.addActionListener (this);
          south.add(new JLabel("  Word Count: "));
          south.add(wordCount);
          cp.add(BorderLayout.CENTER,jsPane);
          cp.add(BorderLayout.SOUTH,south);
     public void actionPerformed(ActionEvent e)
          //if(e.getSource() == jbtCount)   // user clicks Count Words Button
          Object s = e.getSource();
         if ( s instanceof Button )
              jtPane.setDocument(new DefaultStyledDocument() {
                    public void insertString(int offset, String str, AttributeSet as) throws BadLocationException
                       super.insertString(offset,str,as);
                       String text = jtPane.getText();
                       String[] tokens = text.split(" ");
                       wordCount.setText("" + countValid(tokens));
                     public void remove(int offset, int len) throws BadLocationException
                       super.remove(offset,len);
                       String text = jtPane.getText();
                       String[] tokens = text.split(" ");
                         wordCount.setText("" + countValid(tokens));
              else{}
     } // end actionPerformed
     private int countValid(String[] tokens)
          int count = 0;
         for (int i = 0; i < tokens.length; i++)
                if (tokens.trim().length() != 0)
          count++;
     return count;
} // end public class WordCount

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class WordCount extends JFrame implements ActionListener
     JTextPane jtPane = new JTextPane();
     JScrollPane jsPane = new JScrollPane(jtPane);
     JPanel south = new JPanel();
     JTextField wordCount = new JTextField(20);
     JButton jbtCount = new JButton("Count Words");
    public static void main(String[] args)
          int width = 700;
          int height = 300;
           WordCount f = new WordCount();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         f.setSize(width, height);
         f.setTitle("Word Counter");
         f.setLocation(200, 200);
         f.setVisible(true);
    public WordCount()
          super();
          Container cp = getContentPane();
          wordCount.setEditable(false);
          south.setLayout(new FlowLayout(FlowLayout.CENTER));
          south.add(jbtCount);
               jbtCount.addActionListener (this);
          south.add(new JLabel("  Word Count: "));
          south.add(wordCount);
          cp.add(BorderLayout.CENTER,jsPane);
          cp.add(BorderLayout.SOUTH,south);
     public void actionPerformed(ActionEvent e)
          //if(e.getSource() == jbtCount)   // user clicks Count Words Button
          Object s = e.getSource();
              // *** process Button actions
        if ( s instanceof Button )
              jtPane.setDocument(new DefaultStyledDocument() {
                    public void insertString(int offset, String str, AttributeSet as) throws BadLocationException
                       super.insertString(offset,str,as);
                       String text = jtPane.getText();
                       String[] tokens = text.split(" ");
                       wordCount.setText("" + countValid(tokens));
                     public void remove(int offset, int len) throws BadLocationException
                       super.remove(offset,len);
                       String text = jtPane.getText();
                       String[] tokens = text.split(" ");
                         wordCount.setText("" + countValid(tokens));
              else{}
     }// end actionPerformed
     private int countValid(String[] tokens)
          int count = 0;
         for (int i = 0; i < tokens.length; i++)
                if (tokens.trim().length() != 0)
          count++;
     return count;
} // end public class WordCount

Similar Messages

  • Where, if any, Word Count and Word Frequency tools on Apple Works or MS Wrd

    5/26/2008. Is there a "word count" and/or "word frequency" tool(s) on Apple Works word document and/or Microsoft Word for Mac word document, and how does one use or activate it, or find such for it on the web?? Many thanks. C. Yopst, Chicago

    Hi C,
    In an AppleWorks WP document, go Edit > Writing Tools > Word count. This will give you a count of characters, words, lines and paragraphs in the document or, if you have selected a portion of the document, in the selection.
    To my knowledge, there's no tool to give a word frequency figure, although that could be done with some fairly easy manipulation involving a spreadsheet.
    For MS Word questions, I'd suggest checking the Word section of Microsoft's Mactopia site. Try searching "count words".
    Regards,
    Barry

  • What happened to page count, word count and the toolbar at the top?

    Is there any way to edit the toolbar so that when I want to switch fonts I don't have to keep opening the toolbar on the side? (Is there anyway I can get the toolbar from the previous version back?)
    Also, is there a way for the page count and word count to show up and stay there for future documents? I had the word count appear and tried to save that as a template but when trying to open up new documents I have to go back and make it so the word count shows up again.

    What Peter said.
    Is there any way to edit the toolbar so that when I want to switch fonts I don't have to keep opening the toolbar on the side?
    Yes. Menu > View > Customize Toolbar... drag/drop the Fonts icon adjacent to the Comments icon on the Toolbar. The Fonts icon now becomes a toggle to show/hide the Fonts toolbox, which you could also produce with a command+T.
    (Is there anyway I can get the toolbar from the previous version back?
    No.
    Also, is there a way for the page count and word count to show up and stay there for future documents
    No. Available via Menu > View > Show Word Count. This produces a floating box at the bottom of your document. When you roll over it with your mouse, you have a selection of words, characters, and paragraphs. The word count excludes spaces.

  • Word Count and Footnotes

    Hello,
    I have looked at some of the posts on word count but I need to do a word count that automatically includes footnotes. MS Word supports this. Does Pages and, if so, how?
    Many thanks.

    Stephen1965 wrote:
    Thanks for the prompt reply. I should clarify:
    The automatic word count does indeed include footnotes, but if you use the inspector and a selection of text there is no option to include a word count of any footnotes attached to that selection.
    I need to be able to select sections of the document and get a word count that includes the footnotes that belong to that section.
    Feature unavailable but available.
    Select the block of text in the main text layer.
    Grab the word count.
    Select the footnotes.
    Grab the word count.
    Make an addition and you will know the wanted word count.
    _Go to "Provide Pages Feedback" in the "Pages" menu_, describe what you wish.
    Then, cross your fingers, and wait _at least_ for iWork'10
    Yvan KOENIG (VALLAURIS, France) mardi 29 septembre 2009 17:24:31
    Thanks again.

  • Word counts and character counts

    Hi,
    I'm using Pages '06. I would like to be able to count the number of words and characters in a paragraph in Pages. I know that if i go to the Document Inspector and click info, it gives me word and character counts for the entire document. Is there a way to do this for individual paragraphs?
    Many thanks.
    Joe.

    After you install WordService (see link in Dennis' post), you can access several new services in the Pages menu. You may have to restart Pages &/or your Mac.
    WordService & CalcService add their functions to any OS X program that has been programed to utilize Services. I've been using them since shortly after I got iWork '05.

  • Word counting and sorting

    hi i am trying to write a program for a uni project that will -
    choose a file of text
    displays the number of occurrences of each word in the file (together with the word itself),
    then sorts it so that the commonest word is at the top of the list.
    A word to be any sequence of letters and apostrophes.
    All other characters should be treated as separators between words. Lower and upper case letters should be treated as equivalent, so that for example �the� and �The� will not be treated as two different words.
    any help or examples for this would be apprichated a lot
    Jez

    hi, well basically i need help with it all!
    programming isnt my strongest point and i really need
    to do this project well so i can try and come out
    with a 1st, is there anyway that you could write an
    example of this project? i am struggling quite a lot
    with it and you seem like you know what your doing!The easiest way to do the project well is to learn to program well. The easiest way to learn programming is to do it. So for your sake, I won't post complete examples. But here are some links that might help, in addition to the links for maps:
    http://java.sun.com/docs/books/tutorial/essential/io/index.html - I/O tutorial
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html - contains methods for converting between case
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html - contains methods for checking the type of a character
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/StringTokenizer.html - if you can define a set of word delimiters, this could help in chopping the text to words
    Try some things yourself, and we'll try to help you if you run into trouble

  • Putting Word Count in Pages Document

    Is there a way to insert a document's current word count directly into the body of the document? In other words, is there a way to do the equivalent of "Insert Page Number" or "Insert Page Count" for word count?

    PeterBreis0807 wrote:
    See *How to Insert Current Weather and Word Count into Your Document* p307 in the Pages09_UserGuide.pdf downloadable from under the Help menu.
    Peter
    It's dificult to read page 307 in a guide containing 266 pages.
    On page 37 I may read how to view word count and other document statistics but,
    - I saw nothing about current weather
    - I saw nothing about a way to insert the word count in the document as it was asked by the OP
    As far as I know,
    we may insert page num, page count, date time, file name
    but we only
    may display word count.
    Yvan KOENIG (from FRANCE mercredi 27 mai 2009 18:21:12)

  • Insert word count

    Is there a way to insert word count? I have some professors that want a word count and I wanted to know if there was an "insert word count" somewhere?

    No, there isn't. Can't you write it by hand?
    Remember that Pages counts different to how MS Word does.
    _http://discussions.apple.com/thread.jspa?messageID=10937776_
    And read this thread _http://discussions.apple.com/thread.jspa?messageID=10877817_

  • Word Count Funtion?

    Can you select part of a document for a word count and can you determine word count from an entire pages document?

    Yes,
    Click on the Document inspector > Info. That'll give you the word count for the entire doc. Or just select some text for a partial word count.
    -Dennis

  • Is there a way to exclude text from word count?

    Hi,
    I'm writing a research project at the moment and it's about 12000 words. I have to state the word count at the start and it is supposed to exclude everything which comes in reference brackets, eg (Ames, 2009, p.103)
    I want to check the word count at the moment so want to exclude all references from the word count, but I dont want to simply delete them all because I still need to work on the doucment!
    Is there a way to do that?!

    Hi Brigit,
    It can be done (or at least estimated closely) using only tools included in Pages, Here's the process:
    Record the word count at the bottom left of the document window.
    Press command-F to open the Find/Replace dialogue.
    Enter an opening parenthesis character ( "("  without the quotes ) into the Find box.
    Enter the same character into the Replace with box.
    Click Replace all.
    Note the count of items replaced below the Replace box (one in the example, your post above):
    If all in text references are similar to the sample one provided, each contains four 'words'. Multiply the count by four, subtract the result from the document's word count, and you'll have the result you're looking for.
    If your references are of different lengths (eg. (Ames and Smith, 2003, pp.301-303) has a word count of 7), you'll need to adjust the multiplier.
    Note that if you have parentheses in your document that are NOT enclosing references, these will be included in the count.
    Regards,
    Barry

  • Journal app that tracks word count?

    I'd like an app that is able to track daily word count and graph it over time frames so I can see progress.  I want to write X words per day and would like to track this.
    I'd like to group writings as well so it isn't just one long journal and have the ability to track word count per count plus overall (all groups). Does anyone know of an app like this?

    Hi,
    going further, through the selection, modify this alike:
    var
         curDoc = app.activeDocument,
         mySel = app.selection,
         len = mySel.length,
         cStyle = curDoc.characterStyles.item("wordcount"),
         mySelWords, mString, curSel;
    if (!cStyle.isValid)
        cStyle = curDoc.characterStyles.add({name: "wordcount", fontStyle: "Bold"});
         while (len-->0) {
              curSel = mySel[len];
              if (curSel.hasOwnProperty ("insertionPoints") ) {
                   mySelWords = curSel.texts.everyItem().words.length,
                   mString = mySelWords + " Words. ";
                   curSel.insertionPoints[0].appliedCharacterStyle = cStyle;
                   curSel.insertionPoints[0].contents = mString;
    Notice that textFrame.words count is the ones visible only, so overflown part of text is excluded.
    If some answers were helpful - mark it (them ), pls ==> this is a good flag for other searchers..., and some points for me.., mlask.
    Jarek

  • Is there a way to exclude title, heading and bibliography text from the word count in pages?

    I've just got the newest version of pages.
    The word count includes everything, from titles to endnotes - including the numbers in my sub-headings.
    I used to use open office where you could select a style i.e. 'body tex't, and get a word count that didn't include every single word in a document.
    Is there a way of doing something similar, or reseting the word count to only 'body text' so I know exactly how long my essays are?
    Thanks.

    Unfortunately, no version of Pages has this fine-grained control over document components and their word count, so the answer is no, regarding user changeable settings.
    Programmatically, I just told AppleScript to count the words of body text in a currently opened Pages v5.2 document. The count matched the Pages word count for the document. So, no solution there either.

  • Does anyone know why the word count in Word for Mac changes so drastically? In one document it goes up and down by several hundred at a time when I have done nothing but scroll through the document.

    I am new to the wonderful world of Mac and all of my documents were created in MS Word on my old laptop. I noticed that the word counts were slightly different when I opened the documents in Word for Mac, but then I noticed that they changed drastically. For intance, I opened a document today and after the initial period where the word count shifts, it seemed to settle on 13,171. I left the document for a while to work on some other things and when I came back the word count had changed to 11,677. I didn't do anything to the document. Word counts are important to me since I need at least 60,000 for my PhD Dissertation. Which word count should I trust?

    Since Word is a Microsoft product, you should probably post your question on the Microsoft Mac forums:
    http://answers.microsoft.com/en-us/mac

  • After installing lion and updating to pages 4.1 cannot view my document content after I open the document.  Shows how many pages I have and how many words in word count, but no words...

    after installing lion and updating to pages 4.1 cannot view my document content after I open the document.  Shows how many pages I have and how many words in word count, but no words...

    Same problem. Tried reinstalling Pages. Didn't help. The behavior is like I am typing with a white font on a white background, but I am not.

  • Appleworks: word count, footnotes and text frames.

    Hi there!
    Does anybody know if footnotes and text boxes are automatically included in a word processing document word count? If they are, is there a way of excluding these from the word count? Am writing a 12,000 word dissertation, and footnotes and illustration references (which I have put in separate text frames)don't count towards this figure, but some of mine are huge so I'm worried about them distorting the word count.
    Thanks
    ibook G4   Mac OS X (10.4.3)  

    AppleWorks offers an option to Count Selection in the Word Count dialogue. Click in the main body of the text, then press command-A to select all. Then go Edit > Writing tools... > Word count... In the dialogue, click the Count Selection checkbox, and you'll notice the count goes down.
    Unfortunately, this eliminates only the words contained in Text frames, which, as objects, aren't selected along with the text. Footnotes are included in the text selection, and are included in the count.
    To eliminate footnotes (and text in frames) from the count do this:
    •Click in the body text and Select All (command-A)\
    •Copy (command-C)
    •Open a new (temporary) word processor document
    •Paste (command-V)
    •Find/Change (command-F)
    --in Find, enter "\f" (without the quotes) (\f is the marker for a footnote)
    --leave Change empty
    --Click Change All, then OK the warning and the alert telling you how many changes were made.
    •Go Edit > Writing tools...> Word Count.
    •Close the temporary document without saving.
    The process copies the main text and footnotes to a new document, then removes all of the footnotes before you do the word count.
    Regards,
    Barry

Maybe you are looking for

  • Choice between UPK in-application help and standard EBS help

    Hi, We are on a EBS 11.5.10 project, implementing UPK. We got UPK in-application help working; changed custom.pll, set the profile option, everything fine. Now we would like the users to have the choice between UPK help (default) and standard EBS hel

  • I've deleted the recently added and recently played tabs and want to get them back, how?

    Hi I've deleted the recently played, and recently added tabs on the left hand side of itunes, but I now want to gewt them back. I've tried to look online for solutions but they don't work, I get the icon up again, but nothing gets added. Am I doing s

  • Huge tracts of white space padding in topics

    Mostly whenever there is a javascript call, like for a fixed sized popup. This is no a huge problem, but it seems that this also causing trailing spaces after the link to disappear and that is a problem.

  • IPod won't work off the charger

    My 4th Gen iPod won't work when it's not connected to the charger.  As soon as you remove it from the power source it shuts down.  I have updated to the latest iOS and it's been restored.  This corrected the issue for about 24hrs then it was back to

  • Cant sync photos (error 48)

    I was having problems with my 5th generation 30g photo ipod after I Recently upgraded to the latest itunes and updated my ipod software. When I went to Apple support I tried the 5r's as instructed and after i restored my ipod i started getting this e