Java AWT : Number of Character and Number of Words in a TextField

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, LabelTextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Program to demonstrate ActionEvents:Number of Character and Number of Words in a TextField.
Program:

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class TextAreaEg extends Frame implements ActionListener{
TextField t1;
Button b1;
Button b2;
TextAreaEg()
{
t1 = new TextField();
b1= new Button("Chars");
b2 = new Button("Words");
t1.setBounds(100, 100, 300, 300);
b1.setBounds(100,500,50,50);
b2.setBounds(200,500, 50,50);
add(t1);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(1000,1000);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
           dispose();
         }
     }
);

}
@Override
public void actionPerformed(ActionEvent e) {
String s1=t1.getText();
if(e.getSource()==b1)
{
Frame f = new Frame(); 
int l=s1.length();
String s = String.valueOf(l);
Label label1 = new Label("The number of characters is "+s);
f.add(label1);
f.setSize(300,300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            f.dispose();
         }
     }
);
}
else if(e.getSource()==b2)
{
Frame f1 = new Frame(); 
String[] words = s1.split("\\s+");
    int w=words.length;
    String s = String.valueOf(w);
Label label1 = new Label("The number of characters is "+s);
f1.add(label1);
f1.setSize(300,300);
f1.setVisible(true);
f1.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            f1.dispose();
         }
     }
);
}

}
public static void main(String a[])
{
TextAreaEg e = new TextAreaEg();
}


}

Output:

Previous Post Next Post