Count Words and Characters in Java AWT


This Java program creates a GUI application using AWT to display a TextArea along with two Labels and a Button. The program creates a frame using the Frame class and sets its size and layout to null. The frame is made visible using the setVisible() method.

Inside the frame, the program creates two Labels using the Label class and sets their positions and sizes using the setBounds() method. Similarly, a TextArea is created using the TextArea class and its position and size is set using the setBounds() method. Finally, a Button is created using the Button class and its position and size is set using the setBounds() method. An ActionListener is added to the Button using the addActionListener() method. The actionPerformed() method is overridden to handle the button click event.

In the actionPerformed() method, the text entered in the TextArea is retrieved using the getText() method. The split() method is then used to split the text into an array of words by using the regular expression \\s, which matches any whitespace character. The length of the resulting array of words is then calculated and displayed on the first Label using the setText() method. Similarly, the length of the original text is calculated and displayed on the second Label.

The program also includes a WindowListener to handle the window close event using the addWindowListener() method. When the user clicks the close button on the frame, the windowClosing() method is called, which exits the program using the System.exit() method.

Overall, this program demonstrates how to count the number of words and characters in a Java AWT application using a TextArea and other GUI components.

Source Code

package awtDemo;
 
import java.awt.*;
import java.awt.event.*;
 
//Program to Count Words and Characters in Java AWT
class MyApp extends Frame implements ActionListener {
 
	Label l1,l2;
	TextArea t;
	Button b;
 
	public MyApp() {
		super("Word & Letters Count");
		setSize(1000, 600);// w,h
		setLayout(null);
		setVisible(true);
 
 
		l1=new Label("-------");
		l1.setBounds(20,30,200,20);
 
		l2=new Label("-------");
		l2.setBounds(20,60,200,20);
 
		t=new TextArea(10,30);//R C
		t.setBounds(20,100,300,200);
 
		b=new Button("Get Details");
		b.setBounds(20,320,100,30);
		b.addActionListener(this);
 
 
		add(l1);
		add(l2);
		add(t);
		add(b);
 
 
		// Close Button Code
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				System.exit(0);
			}
		});
	}
 
	@Override
	public void actionPerformed(ActionEvent e) {
		    String text = t.getText();    
		    String words[]=text.split("\\s");    
		    l1.setText("Words: "+words.length);    
		    l2.setText("Characters: "+text.length());   
 
	}
 
}
 
public class app {
	public static void main(String[] args) {
		MyApp frm = new MyApp();
	}
 
}
 
To download raw file Click Here

Output

Java AWT


Basic Programs