We can create many different GUI through coding that can help us in many different ways. This is an interface to count the number of words and characters of any write-up. It has an area to type the text or copy-paste the test with two buttons to run either word or character counting functions.
When you run the code, you will see GUI like the following;
You can type anything you want. I typed the following text into the white text area:
When you click on the “Word” button, you will see a message window that shows the number of words in your text.
When you click on the “Character” button, you will see a message window that shows the number of characters in your text.
The following is the code. Go head, open your NetBeans and test it;
package wordcounter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class WordandCharaterCounter extends JFrame implements ActionListener
{
JTextArea textA;
JButton button1, button2;
WordandCharaterCounter()
{
super(“Word and Character Counter”);
textA = new JTextArea();
textA.setBounds(30, 30, 400, 250);
button1 = new JButton(“Word”);
button1.setBounds(50,300,100,30);
button2 = new JButton(“Character”);
button2.setBounds(180, 300, 100, 30);
button1.addActionListener(this);
button2.addActionListener(this);
add(button1);
add(button2);
add(textA);
setSize(500, 500);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
String text = textA.getText();
if (e.getSource() == button1)
{
String words[] = text.split(“\\s”);
JOptionPane.showMessageDialog(this, “Total words: ” + words.length);
}
if (e.getSource() == button2)
{
JOptionPane.showMessageDialog(this, “Total Characters with space: ” + text.length());
}
}
public static void main(String[] args)
{
new WordandCharaterCounter();
}
}
