In this tutorial, we will create a Word Counter in Java using Swing for the graphical user interface (GUI). The app will allow users to input text, and it will display the total word count as well as the character count.
The app will update the count dynamically when the user types in the text area.
Features of the Word Counter App:
The app provides a text area for the user to enter text.
The app calculates and displays:
Word count: The total number of words in the text.
Character count: The total number of characters in the text (including spaces).
The app updates the word and character counts in real-time as the user types.
Complete Code
import javax.swing.*; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class WordCounterApp extends JFrame { private JTextArea textArea; // Text area where the user types private JLabel wordCountLabel; // Label to display word count private JLabel charCountLabel; // Label to display character count // Constructor to set up the GUI public WordCounterApp() { setTitle("Word Counter"); setSize(500, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Center the window on the screen // Create a text area for input textArea = new JTextArea(); textArea.setFont(new Font("Serif", Font.PLAIN, 18)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); // Add key listener to update the word and character counts in real-time textArea.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { updateCounts(); } }); // Create labels to display word and character counts wordCountLabel = new JLabel("Word Count: 0"); charCountLabel = new JLabel("Character Count: 0"); // Panel to hold the count labels JPanel countPanel = new JPanel(new GridLayout(1, 2)); countPanel.add(wordCountLabel); countPanel.add(charCountLabel); // Set layout for the frame setLayout(new BorderLayout()); add(new JScrollPane(textArea), BorderLayout.CENTER); add(countPanel, BorderLayout.SOUTH); setVisible(true); } // Method to update word and character counts private void updateCounts() { String text = textArea.getText(); String[] words = text.trim().split("\\s+"); // Split based on spaces int wordCount = (text.trim().isEmpty()) ? 0 : words.length; int charCount = text.length(); // Update labels wordCountLabel.setText("Word Count: " + wordCount); charCountLabel.setText("Character Count: " + charCount); } // Main method to run the app public static void main(String[] args) { SwingUtilities.invokeLater(() -> new WordCounterApp()); } }
Explanation of the Code
1. Import Statements
import javax.swing.*; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; javax.swing.*: Provides Swing components such as JFrame, JTextArea, and JLabel for creating the GUI. java.awt.*: Provides layout and graphical utilities (e.g., BorderLayout, GridLayout, Font). java.awt.event.*: Provides event listener classes for handling keyboard events.
2. Class Declaration and Instance Variables
public class WordCounterApp extends JFrame { private JTextArea textArea; // Text area where the user types private JLabel wordCountLabel; // Label to display word count private JLabel charCountLabel; // Label to display character count } JTextArea textArea: A multi-line text area where the user can type text. It supports word wrapping. JLabel wordCountLabel: A label that displays the current word count. JLabel charCountLabel: A label that displays the current character count.
3. Constructor
public WordCounterApp() { setTitle("Word Counter"); setSize(500, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Center the window on the screen // Create a text area for input textArea = new JTextArea(); textArea.setFont(new Font("Serif", Font.PLAIN, 18)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); // Add key listener to update the word and character counts in real-time textArea.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { updateCounts(); } }); // Create labels to display word and character counts wordCountLabel = new JLabel("Word Count: 0"); charCountLabel = new JLabel("Character Count: 0"); // Panel to hold the count labels JPanel countPanel = new JPanel(new GridLayout(1, 2)); countPanel.add(wordCountLabel); countPanel.add(charCountLabel); // Set layout for the frame setLayout(new BorderLayout()); add(new JScrollPane(textArea), BorderLayout.CENTER); add(countPanel, BorderLayout.SOUTH); setVisible(true); }
Frame Setup:
setTitle(“Word Counter”): Sets the window title.
setSize(500, 300): Sets the window size.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the app exits when the window is closed.
setLocationRelativeTo(null): Centers the window on the screen.
Text Area Setup:
textArea = new JTextArea(): Creates the text area for typing.
textArea.setFont(new Font(“Serif”, Font.PLAIN, 18)): Sets the font for the text area.
textArea.setLineWrap(true): Enables word wrapping.
textArea.setWrapStyleWord(true): Ensures that words are not cut off when wrapping.
Key Listener Setup:
textArea.addKeyListener(new KeyAdapter() { … }): Adds a key listener to the text area that updates the word and character counts whenever a key is released.
Count Labels Setup:
wordCountLabel: Displays the current word count.
charCountLabel: Displays the current character count.
Panel Setup:
JPanel countPanel = new JPanel(new GridLayout(1, 2)): Creates a panel to hold the two labels with a grid layout of 1 row and 2 columns.
Adds the word count and character count labels to the panel.
Layout Setup:
setLayout(new BorderLayout()): Uses a BorderLayout to position components.
add(new JScrollPane(textArea), BorderLayout.CENTER): Adds a scrollable text area to the center of the window.
add(countPanel, BorderLayout.SOUTH): Adds the panel with the count labels to the bottom of the window.
4. updateCounts() Method
private void updateCounts() { String text = textArea.getText(); String[] words = text.trim().split("\\s+"); // Split based on spaces int wordCount = (text.trim().isEmpty()) ? 0 : words.length; int charCount = text.length(); // Update labels wordCountLabel.setText("Word Count: " + wordCount); charCountLabel.setText("Character Count: " + charCount); } textArea.getText(): Retrieves the text entered in the text area.
Word Counting:
text.trim().split(“\\s+”): Splits the text into words based on one or more spaces. trim() removes any leading or trailing whitespace.
(text.trim().isEmpty()) ? 0 : words.length: If the trimmed text is empty, the word count is set to 0; otherwise, the length of the words array is used as the word count.
Character Counting:
text.length(): The length of the string is used to calculate the character count, including spaces.
Updating Labels:
wordCountLabel.setText(“Word Count: ” + wordCount): Updates the word count label.
charCountLabel.setText(“Character Count: ” + charCount): Updates the character count label.
5. Main Method
public static void main(String[] args) { SwingUtilities.invokeLater(() -> new WordCounterApp()); } SwingUtilities.invokeLater(): Ensures that the GUI is created and updated on the Event Dispatch Thread (EDT), which is necessary for Swing applications. new WordCounterApp(): Creates and launches the word counter app.
Customization Ideas
1. Add a File Input Option
Add a button to allow the user to load text from a file (JFileChooser). The word and character counts would then be calculated for the file content.
2. Display Additional Statistics
Display additional statistics such as:
Sentence count
Paragraph count
Longest word
3. Improve the User Interface
Change the fonts, colors, or layout to improve the appearance of the app.
Add icons to buttons or use tooltips for added usability.
4. Add Real-time Copying to Clipboard
Add a button to copy the entire text or just the word/character counts to the clipboard for use in other applications.
Conclusion
This Word Counter App in Java using Swing is a simple, yet useful, application that allows users to count the number of words and characters in a text.
The app includes:
Using Swing components (JFrame, JTextArea, JLabel) to create a graphical interface.
Updating the word and character counts dynamically as the user types.
Handling keyboard events with KeyListener to trigger real-time updates.
Feel free to expand this project with additional features or improvements to suit your needs!